-3

What's the best way to create a N levels nested object (where N is the size of the array) for example:

const arr = ['a','b','c','d']

The output object should look like this:

{
  a: {
    b: {
      c: {
        d: true
      }
    }
  }
}
2
  • 1
    Please also include the code that you wrote that isn't properly working. Commented Sep 5, 2019 at 14:35
  • Use reduceRight with true as initialValue arr.reduceRight((r, k) => ({ [k]: r }), true) Commented Sep 5, 2019 at 14:41

1 Answer 1

3

You can use array.reduce, it helps you pass an accumulator where you can accumulate your nested obj.

const array = ['a','b','c','d'];
const object = {};
array.reduce((o, s) => { 
  return o[s] = {};
}, object);
console.log(object);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.