JSON数组 - 使用Javascript提取数据

时间:2013-10-18 14:30:28

标签: javascript ajax arrays json

我有一个非常简单的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":[]}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

假设您将对象保存在变量jObj中,克隆数组/对象,以便保留原始文件,sort根据需要然后返回一个 Array ,它只包含 name 属性。

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"
] */