我有一个非常简单的Json数组,我需要回来
数组如下:
{"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":[]}
答案 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"
] */