1

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.

3
  • 2
    please add your try. Commented Jun 30, 2020 at 7:46
  • 3
    look away to reduce Commented Jun 30, 2020 at 7:48
  • 1
    Yes, basically you want to iterate through every element in the array and do a custom aggregation, which reduce is perfect for. Alternatively you can use a for loop to iterate over the set. Commented Jun 30, 2020 at 7:50

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Just keep in mind that if the data source is untrusted, this is susceptible to prototype pollution. Consider ['__proto__', 'toString', 123] as input. This problem exists with any simple approach unless special countermeasures are taken (skip __proto__ and constructor) or a library is used that takes them for you.
Wow this solution is so elegant and beautiful. Time to say goodbye to for loops for good. I am gonna learn more about functional programming now.
I was working on an answer but wasn't as good. I pasted Nina's answer into a sandbox here codesandbox.io/s/peaceful-mcnulty-8lcbv?file=/src/index.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.