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.
CodePudding user response:
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)