[英]How to put values from an array of objects into a new array in JavaScript
I have this array of objects: 我有这个对象数组:
const array = [
{id: 35, id_city: 27, id_district: 453},
{id: 36, id_city: 27, id_district: 454}
];
I expect to get the "id_district" values into a new array so the result should be: 我希望将“ id_district”值放入新数组,因此结果应为:
const ArraydDistrict = [453,454];
I guess the answer is simple, I am just really new at this so any help would be appreciated. 我想答案很简单,对此我真的很陌生,所以我们将不胜感激。 Thank you
谢谢
You can use Array.map
to return the values. 您可以使用
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]
You could also use an implicit return to reduce verbosity. 您也可以使用隐式返回来减少冗长。
const result = array.map(el => el.id_district)
If you want to be fancy, ES6
lets you do this 如果您想花哨的话,
ES6
可以让您做到这一点
const result = Array.from(array, el => el.id_district)
It seems like a use case for Array.map 似乎是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);
Take a look at Array.map, Array.filter, Array.reduce all these functions come pretty handily in array processing. 看一下Array.map,Array.filter,Array.reduce,所有这些函数在数组处理中都很方便。
You can use the following solution to put values from an array of objects into a new array in JavaScript: 您可以使用以下解决方案将对象数组中的值放入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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.