I have an object like this:
obj1 = {A: {bottom: 63, mid: 4, top: 15}, B: {bottom: 30, mid: 23, top: 5}, C: {bottom: 41, mid: 25, top: 16}}
and I'm trying to convert to something like this:
obj2 =
{group: "A", bottom: "63", mid: "4", top: "15"}
{group: "B", bottom: "30", mid: "23", top: "5"}
{group: "C", bottom: "41", mid: "25", top: "16"}
by following this post but I'm getting an error obj1[key].forEach is not a function any ideas why I'm getting this error?
this is the code I'm using which is basically the same from the original:
obj1 ={A: {bottom: 63, mid: 4, top: 15}, B: {bottom: 30, mid: 23, top: 5}, C: {bottom: 41, mid: 25, top: 16}}
const result = []
// for each key in obj
Object.keys(obj1).forEach(key => {
// for each array element of the property obj[key]
obj1[key].forEach((value, index) => {// in this line I'm getting the error
// if an object doesn't exists at the current index in result
// create it
if (!result[index]) {
result[index] = {}
}
// at the result index, set the key to the current value
result[index][key] = value
})
})
console.log(result)
You are getting error because of this line obj1[key].forEach((value, index), because it is an object and you are trying to use forEach on an object.
For example obj1[key] will give the value of A and B etc keys which as an object like {bottom: 63, mid: 4, top: 15}.
You can us only for..in and then use destructing to push the values in the array
const obj1 = {
A: {
bottom: 63,
mid: 4,
top: 15
},
B: {
bottom: 30,
mid: 23,
top: 5
},
C: {
bottom: 41,
mid: 25,
top: 16
}
}
const result = []
for (let key in obj1) {
result.push(Object.assign({}, obj1[key], {
group: key
}))
}
console.log(result)
forEach is available on arrays, but during the first iteration obj1[key] is effectively obj1.A, which returns an object {bottom: 63, mid: 4, top: 15}, which doesn't have forEach, hence the error.
This might be a good use of reduce:
obj1 = {A: {bottom: 63, mid: 4, top: 15}, B: {bottom: 30, mid: 23, top: 5}, C: {bottom: 41, mid: 25, top: 16}}
const result = Object.entries(obj1).reduce(
// group is the key from obj1, e.g. "A"
// properties is the object for that key, e.g. { bottom: 63, mid: 4, top: 15 }
(acc, [group, properties]) => [
...acc, { group, ...properties }
], []
);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With