How to create Object with nested Objects from an Array

Viewed 447

I have an array [1, 2, 3] and I want to transfer it to object with nested parent-child objects's series like this :

{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } } 

If I have an array [1, 2, 3, 4] the result will be like this :

{ value: 1, rest: { value: 2, rest: { value: 3, rest: { value:4, rest:null } } 

The best effort of me is this snippet of code :

const arrayToList = (array) => {
  let list = { value: null, rest: null };
  for (let e of array) {
    array.indexOf(e) === 0 && (list.value = e);
    array.indexOf(e) >= 1 && (list.rest = { value: e });
  }
  return list;
};
console.log(arrayToList([1, 2, 3]));

4 Answers

You can use reduceRight like so:

let obj = arr.reduceRight((rest, value) => ({ value, rest }), null);

It starts building the object from the inside out; it starts by creating the innermost object and then it uses that object as the rest property for the next outer object and so on until there are no more items in the array.

Demo:

let obj = [1, 2, 3, 4].reduceRight((rest, value) => ({ value, rest }), null);

console.log(obj);

You can create such object by running below recursive function:

let arr = [1, 2, 3, 4];

let transform = (arr, obj) => {
   if(arr.length === 0){
      return obj;
   } else {
      let last = arr[arr.length - 1];
      let newArr = arr.slice(0, arr.length - 1);
      
      return transform(newArr, { value: last, rest: obj || null })
   }
};

console.log(transform(arr));

Use a recursive function:

let array = [1, 2, 3];

function arrayToL(array) {
  let el = array.splice(0, 1)[0];
  let rtn = {
    value: el
  }

  rtn.rest = (array.length > 0) ? arrayToL(array) : null;

  return rtn;
}

console.log(arrayToL(array));

I suggest another solution using the spread operator and reversing the array and start building object from the array end :

let arr = [1, 2, 4, 5]

let obj = {} //object to be built

arr.slice().reverse().forEach(item => { //i used the slice method 
  //in order to avoid mutating
  //the original variable
  obj = { ...obj,
    ...{
      value: item,
      rest: obj
    }
  };

})

console.log(obj)

Related