1

How would you create a deeply nested object from an array. Like so...

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

to...

{
  a: {
    b: {
      c: {
        d: {}
      }
    }
  }
}

and potentially as deep as there are elements in the array..

1
  • In short... a.reduceRight((p, c) => ({ [c]: p }), {}) Commented Mar 9, 2017 at 4:34

1 Answer 1

2

Use Array#reduce method.

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

let res = {};

a.reduce((obj, e) => obj[e] = {}, res)

console.log(res)


Or with Array#reduceRight method.

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

let res = a.reduceRight((obj, e) => ({ [e]: obj }), {})

console.log(res)

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

2 Comments

How did you answer after I closed the question?
That's pretty cool returning the assignment in the first snippet :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.