How to make a nested object out of an array

Viewed 72

given an array like [‘a’, ‘b’, ‘c’]

how can i get an object like

{
  current: ‘a’,
  next : { 
    current: ‘b’,
    next: {
      current: ‘c’
    }
  }
}
2 Answers

You can make a recursive function for this:

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

function createObj([current, ...rest]) {
    const result = { current };
    if (rest.length) result.next = createObj(rest);
    return result;
}

console.log(createObj(data));

The [current, ...rest] is a single destructured array argument.

You can use Array.reduceRight() to create the object:

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

const obj = arr.reduceRight((acc, o) => ({
  current: o,
  ...acc && { next: acc }
}), null)

console.log(obj)

Related