gameFrenzy07
gameFrenzy07

Reputation: 397

How to convert an array into an object of specific format?

Although it is a common problem but I couldn't find any lead to get the desired result. So here is the problem. I have the following array:

[
    [ 'a' ]
    [ 'a', 'b' ]
    [ 'a', 'c' ]
    [ 'a', 'c', 'd' ]
    [ 'a', 'c', 'd', 'e' ]
]

And what I want as an end result is an object like this:

{
  a: {
    b: {},
    c: { d: { e: {} } }
  }
}

I don't understand which approach would be better to get this result and how to achieve it.

Upvotes: 1

Views: 93

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You need a double reduce, one for the outer array and one for the keys and the nesting objects.

var data = [['a'], ['a', 'b'], ['a', 'c'], ['a', 'c', 'd'], ['a', 'c', 'd', 'e']],
    result = data.reduce((r, keys) => {
        keys.reduce((o, k) => o[k] = o[k] || {}, r);
        return r;
    }, {});

console.log(result);

Upvotes: 4

Related Questions