我有这个对象数组:
const array = [
{id: 35, id_city: 27, id_district: 453},
{id: 36, id_city: 27, id_district: 454}
];
我希望将“ id_district”值放入新数组中,因此结果应为:
const ArraydDistrict = [453,454];
我想答案很简单,对此我真的很陌生,所以我们将不胜感激。谢谢
答案 0 :(得分:4)
您可以使用Array.map
返回值。
const array = [
{id: 35, id_city: 27, id_district: 453},
{id: 36, id_city: 27, id_district: 454},
];
const result = array.map(el => { return el.id_district})
//Results in [453, 454]
您还可以使用隐式返回来减少冗长程度。
const result = array.map(el => el.id_district)
如果想花哨的话,ES6
可以帮助您
const result = Array.from(array, el => el.id_district)
答案 1 :(得分:3)
这似乎是Array.map的用例
const arr = [{id: 35, id_city: 27, id_district: 453},{id: 36, id_city: 27, id_district: 454}];
const processedArr = arr.map(o => o.id_district);
console.info(processedArr);
看看Array.map,Array.filter,Array.reduce,所有这些函数在数组处理中都很方便。
答案 2 :(得分:0)
您可以使用以下解决方案将对象数组中的值放入JavaScript中的新数组中:
const ArraydDistrict = [];
const array = [
{id: 35, id_city: 27, id_district: 453},
{id: 36, id_city: 27, id_district: 454},
];
array.forEach(function(item) {
ArraydDistrict.push(item.id_district);
});
console.log(ArraydDistrict);