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.
mapfunction is attempting to destructurekeyfrom the objects inarr, but there's no such property. AlsoObject.entries(arr)seems unusual; you can iterate over an array in easier ways.