简体   繁体   中英

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:

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.

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

const result = Array.from(array, el => el.id_district)

It seems like a use case for 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.

You can use the following solution to put values from an array of objects into a new array in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM