0

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!

1
  • No, you'll have to iterate over each array element. Commented Nov 17, 2021 at 19:08

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

7 Comments

Inside map return eachObject.color not console logit
Ik, just to help him understand
He wants an array of only colors. He doesn't ask for display them!
and loop for it again to get values? why not use them directly :/
Thanks for all the answers. Thats not too complex, good!
|
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)

Comments

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.