Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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)
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!