1

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.

Autumn Leonard
  • 514
  • 8
  • 22
  • 1
    I don't think there's any built-in way to do this. Just write a loop. – Barmar Jul 08 '16 at 16:26
  • Do you want the keys to be in any particular order? I notice that they're alphabetical in your example, but the order of keys in an object is not guaranteed. – Rose Kunkel Jul 08 '16 at 16:26
  • 2
    @PraveenKumar This isn't the same as that, because he wants an extra level of nesting added. – Barmar Jul 08 '16 at 16:32
  • 1
    Do functions that perform implicit looping, like `.map()`, count as loops in your search for something more elegant? – Barmar Jul 08 '16 at 16:33

2 Answers2

5

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);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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;
}, []);
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Why `reduce` instead of `map`? – Barmar Jul 08 '16 at 16:28
  • Eh, good call @Barmar; not sure why I went with reduce instead of map...it's early? – Rob M. Jul 08 '16 at 16:29
  • There seems to be a tendency for people to look for clever ways to use `reduce` when it's not really appropriate, it's one of my pet peeves. – Barmar Jul 08 '16 at 16:31
  • @Barmar understandable, I always use reduce to turn arrays into objects, and I think my morning brain had me confusing the operation, updated my answer with map – Rob M. Jul 08 '16 at 16:32