0

I have an array like

array(
  [0] => value1
  [1] => value2
  [3] => value3
   .
   .
  [n] => valuen
)

I want this array values as object key like

object{"value1":{"value2":{"value3":"..."}}}

How can I achieve this.

Thanks in advance

1
  • What will the value be of the inner-most property in the result? The last value from the array? Anyway, the .reduce() method or a simple loop will do the trick. Commented Nov 23, 2017 at 2:28

1 Answer 1

0

Use Array.reduce

const result = arr.reverse().reduce((acc, cur) => ({[cur]: acc}), {});

Example:

const result = ['a', 'b', 'c', 'd'].reverse().reduce(
  (acc, cur) => ({[cur]: acc}), {});

console.log(result); // {a: {b: {c: {d: {}}}}}
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.