Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS: select the same attribute in every object in an array

If I have an array of objects, for example:

var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]

Is there a simple way Im not seeing to select all the "color" attributes? So that I would get:
"red", "green"

So say something like (INVENTED):
console.log(cars[selectingallobjects].name)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

>Solution :

There isn’t a ready way of doing that, you need to iterate to get the values.

You can use .map(), an Array method that creates a new array based on the values returned from the function.

It can be done in a single line.

See below:

var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]

let result = cars.map(car => car.color)

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading