Reputation: 23
I have an object which has objects inside in it at the following form:
Object {
"item1": { "subitem1": 5, "subitem2": 10 },
"item2": { "subitem1": 3, "subitem2": 12, "subitem3": 1 },
"item3": { "subitem1": 8, "subitem2": 1, "subitem3": 3 }
}
I want to convert it to an array with the following form:
[0] Object { key: "item1", "subitem1": 5, "subitem2": 10 }
[1] Object { key: "item2", "subitem1": 3, "subitem2": 12, "subitem3": 1 }
[2] Object { key: "item3", "subitem1": 8, "subitem2": 1, "subitem3": 3 }
Any ideas? Thanks in advance
Upvotes: 1
Views: 36
Reputation: 50639
You can use Object.keys() and Array.prototype.map():
const obj = { "item1": { "subitem1": 5, "subitem2": 10 }, "item2": { "subitem1": 3, "subitem2": 12, "subitem3": 1 }, "item3": { "subitem1": 8, "subitem2": 1, "subitem3": 3 }},
res = Object.keys(obj).map(key => ({key, ...obj[key]}));
console.log(res);
Do note, however, the order of the keys retrieved from Object.keys
is not guaranteed to be the same order as listed in your object
Upvotes: 1
Reputation: 386519
You could get the entries of the object and assign the key.
var object = { item1: { subitem1: 5, subitem2: 10 }, item2: { subitem1: 3, subitem2: 12, subitem3: 1 }, item3: { subitem1: 8, subitem2: 1, subitem3: 3 } },
result = Object.entries(object).map(([key, o]) => Object.assign({ key }, o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 37757
You can try this mate
let obj = { "item1": { "subitem1": 5, "subitem2": 10 }, "item2": { "subitem1": 3, "subitem2": 12, "subitem3": 1 }, "item3": { "subitem1": 8, "subitem2": 1, "subitem3": 3 } };
let op =[];
for(let key in obj){
op.push({
key : key,
...obj[key]
})
}
console.log(op);
Upvotes: 0