Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Object with nested Objects from an Array

Tags:

javascript

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]));
like image 225
Menai Ala Eddine - Aladdin Avatar asked Jun 20 '20 00:06

Menai Ala Eddine - Aladdin


People also ask

How can we convert array to object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

How do I create a nested object in JavaScript?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.

How do you use nested arrays?

After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested ...


1 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);
like image 131
ibrahim mahrir Avatar answered Oct 14 '22 02:10

ibrahim mahrir