0

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

3
  • yes.I now map @Bergi Commented Sep 21, 2018 at 16:48
  • Possible duplicate of Read object within array in nodejs Commented Sep 21, 2018 at 16:49
  • @MohammedAshfaq Thanks, it really help. Commented Sep 21, 2018 at 16:53

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

You can also omit the idx parameter to reduce verbosity…
@Bergi Yeah thanks, just a bad habit I got into because I often use the index :)
3

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.

Comments

1

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);

1 Comment

@MikeM also known as "reinventing the wheel"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.