1

我有一个非常简单的 Json 数组,我需要返回

  • 数组中的项目数。
  • 按 id 顺序排列的条目列表。

数组如下:

{"error":false,"error_msg":"","body":
{"records":[{"name":"Application","id":1},
            {"name":"Fees Paid","id":2},
            {"name":"Evidence Verification","id":3},
            {"name":"Details QA","id":4},
            {"name":"Grade Approval","id":5},
            {"name":"Welcome Pack","id":6}]
},
"validation_errors":[]}
4

2 回答 2

3

假设您已将JSON.parse字符串转换为名为 的变量jsonobj,则以下语句将获取您想要的数据:

var len = jsonobj.body.records.length;
jsonobj.body.records.sort(function(a,b) {return a.id-b.id;});
// now iterate through jsonobj.body.records and they will be in ascending ID order
于 2013-10-18T14:36:12.830 回答
1

假设您将Object保存在 variable 中jObj,克隆Array/Objects以便保留原件,sort然后根据需要返回一个仅包含name属性的Array 。

jObj['body']['records']
    .map(function (e) {return {'id': e['id'], 'name': e['name']};}) // clone
    .sort(function (a, b) {return +a['id'] - +b['id'];})            // sort asc
    .map(function (e) {return e['name'];});                         // get names
/* [
    "Application", "Fees Paid",      "Evidence Verification",
    "Details QA",  "Grade Approval", "Welcome Pack"
] */
于 2013-10-18T14:39:47.233 回答