skip to Main Content

i have the Array in js, but how to convert to object with nesting childs ?

This is my array:

const arr = [{ no: 1 }, { no: 2 }, { no: 3 }];

this is output my expected:

// output
const obj = { no: 1, nest: [{ no: 2, nest: [{ no: 3 }] }] };

3

Answers


  1. You can do it by arr.reduceRight.
    Here is an example –

    const arr = [{ no: 1 }, { no: 2 }, { no: 3 }];
    const obj = arr.reduceRight((acc, curr) => ({...curr, nest: [acc]}));
    console.log(obj);
    

    output:

    { no: 1, nest: [ { no: 2, nest: [Array] } ] }
    
    Login or Signup to reply.
  2. using reduce

    const result = arr.reverse().reduce((acc, curr) => {
      return {no: curr.no, nest: [acc]}
    })
    
    // result is { no: 1, nest: [{ no: 2, nest: [{ no: 3 }] }] };
    
    Login or Signup to reply.
  3. You want to right reduce your array. With reference to this Array.prototype.reduceRight()

    Example:

        const arr = [{ no: 1 }, { no: 2 }, { no: 3 }];
        const result = array1.reduceRight((accumulator, currentValue) =>
        accumulator.concat(currentValue),);
        console.log(result);

    Output:

    { no: 1, nest: [ { no: 2, nest: [Array] } ] }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search