我有这样的JSON数据:
{ "krs_semester": [
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "0b38a133282251406979ba675b896ec5",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000007",
"sks": "2",
"status": "1"
},
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "6130bfc0ec155ff195ecc8dda6d0344c",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000005",
"sks": "2",
"status": "1"
},
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "a12f7877cdd71e79660534d898ffa027",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000006",
"sks": "2",
"status": "1"
}]
}
我这样做是将所有kodesmt
提取到一个数组中
var kmk = [];
var idx=0
$.each(data.krs_semester, function(key, val){
kmk[idx] = val.kodemk;
idx++;
})
所以,我有这个kmk
数组
["13000007", "13000005", "13000006"]
有没有更简单,更有效的方法来做到这一点?
答案 0 :(得分:2)
我将使用map()
函数:
var kmk = data.krs_semester.map(function (c) {
return c.kodemk;
});
或在ES6中:
var kmk = data.krs_semester.map(c => c.kodemk);
工作摘要
var data = { "krs_semester": [
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "0b38a133282251406979ba675b896ec5",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000007",
"sks": "2",
"status": "1"
},
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "6130bfc0ec155ff195ecc8dda6d0344c",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000005",
"sks": "2",
"status": "1"
},
{ "id_krs": "6723b92dd027470822d3914f8be178bd",
"id_belanja": "a12f7877cdd71e79660534d898ffa027",
"nimhs": "51016002",
"kodesmt": "20182",
"kodemk": "13000006",
"sks": "2",
"status": "1"
}]
};
var kmk = data.krs_semester.map(function (c) {
return c.kodemk;
});
console.log(kmk);