youngmago
youngmago

Reputation: 57

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)

Thanks in advance!

Upvotes: 0

Views: 1574

Answers (3)

XMehdi01
XMehdi01

Reputation: 1

Using for-loop and take only color property

var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]
var carNames = []
for(car of cars){
  carNames.push(car['color'])
}
console.log(carNames)// [ "red", "green" ]

use map which is method creates a new array:

var carNames = cars.map(car=>car.color)

Upvotes: 1

Calvin Nunes
Calvin Nunes

Reputation: 6516

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)

Upvotes: 2

Soufiane
Soufiane

Reputation: 160

you can use map to do the following, it loops for every object in the array.

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

cars.map((eachObject)=>{
  console.log(eachObject.color);
});

Upvotes: 1

Related Questions