Reputation: 511
I'd like to convert an object to an array of smaller, single-property objects in Javascript. For example:
x={
a: {a1:"a1", a2:"a2"},
b: {b1:"b1", b2:"b2"},
c: {c1:"c1", c2:"c2"}
}
converted to
y=[
{a: {a1:"a1", a2:"a2"}},
{b: {b1:"b1", b2:"b2"}},
{c: {c1:"c1", c2:"c2"}}
]
I know this is possible with loops, but I was wondering if there is a more elegant way. I'm using underscore/lo-dash if they help.
Upvotes: 1
Views: 108
Reputation: 386520
You could use Array#map
for it.
var x = { a: { a1: "a1", a2: "a2" }, b: { b1: "b1", b2: "b2" }, c: { c1: "c1", c2: "c2" } },
y = Object.keys(x).map(function (k) {
var o = {};
o[k] = x[k];
return o;
});
console.log(y);
ES6 @Nenad Vracar
var x = { a: { a1: "a1", a2: "a2" }, b: { b1: "b1", b2: "b2" }, c: { c1: "c1", c2: "c2" } },
y = Object.keys(x).map(k => ({[k]: x[k]}));
console.log(y);
Upvotes: 5
Reputation: 36511
As Barmar pointed out, it does make more sense to use map
(I left my reduce
versions for posterity):
let arr = Object.keys(x).map(key => { [key]: x[key] });
You can use reduce
to turn it into an array:
Object.keys(x).reduce(function(acc, key) {
var tmp = {};
tmp[key] = x[key];
acc.push(tmp);
return acc;
}, []);
And if ES6 is available, you can make it a bit more concise:
Object.keys(x).reduce((acc, key) => {
acc.push({ [key]: x[key] });
return acc;
}, []);
Upvotes: 1