Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading