Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a nested object out of an array

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

how can i get an object like

{
  current: ‘a’,
  next : { 
    current: ‘b’,
    next: {
      current: ‘c’
    }
  }
}
like image 237
RenaissanceProgrammer Avatar asked Dec 23 '22 15:12

RenaissanceProgrammer


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.

like image 124
Kelvin Schoofs Avatar answered Dec 25 '22 05:12

Kelvin Schoofs


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)
like image 43
Ori Drori Avatar answered Dec 25 '22 05:12

Ori Drori