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

169
Views
Creating an array from each key in an array of objects

I have an array that looks similar to this: The array of objects is much larger and each object has more properties, this is the structure though.

  let arr = [
    { id: 1, name: "tony", hatColor: "blue" },
    { id: 2, name: "larry", hatColor: "red" },
    { id: 3, name: "stuart", hatColor: "green" },
  ];

I want to create an array for each key in this array so I have an array with all ids, an array with all names, and one with all hatColors.

idArr = [1, 2, 3];
nameArr = [tony, larry, stuart];
hatColorArr = [blue, red, green];

I won't know exactly what the array of objects looks like as it is returned from another script.

What I have tried is:

  for (var [key, value] of Object.entries(arr)) {
    for (var [key, value] of Object.entries(value)) {
      var result = arr.map(({ key }) => key);
      console.log(result);
    }
  }

This returns an array of undefined. I hope there is a way to do this, I don't want to write a lot of hard coded if push statements to get this to work.

Thanks.

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

0

You can use Array.map to extract the property values for each item in the array.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"}];

function groupPropValues(objs, prop){
    return objs.map(e => e[prop])
}

idArr = groupPropValues(arr, 'id');
nameArr = groupPropValues(arr, 'name');
hatColorArr = groupPropValues(arr, 'hatColor');
console.log(idArr, nameArr, hatColorArr)

If you want to automatically generate the arrays, you can do so by getting the properties of each object in the array, then fetching the values and storing them in an object.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"}];

function groupPropValues(objs, prop) {
  return objs.map(e => e[prop])
}

const props = [...new Set(arr.reduce((a,b) => (a.push(Object.keys(b)), a), []).flat())]

const result = props.reduce((a,b) => (a[b] = groupPropValues(arr, b), a), {})

console.log(result)

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!