Home > database >  JS: select the same attribute in every object in an array
JS: select the same attribute in every object in an array

Time:11-18

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!

CodePudding user response:

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);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
  • Related