Search code examples
javascriptarrayslodashflatten

Flatten multi dimension array object to one dimensional array object


i am having trouble to converting multidimensional array something like this and need help to flatten this array object into single dimensional array object.

let data = [
  {
    parent_id: 1,
    name: "parent 1",
    child: [
      {
        child_id: 3,
        name: "child 1",
        child: [
          {
            grand_child_id: 5,
            name: "grand child 1",
          },
          {
            grand_child_id: 6,
            name: "grand child 2",
          },
        ],
      },
    ],
  },
  {
    parent_id: 2,
    name: "parent 2",
    child: [
      {
        child_id: 4,
        name: "child ",
        child: [
          {
            grand_child_id: 7,
            name: "grand child 3",
          },
          {
            grand_child_id: 8,
            name: "grand child 4",
          },
        ],
      },
    ],
  },
];

I have try using flatMap() but the result is not what i`m expecting, I'm hoping the result is single dimensional array like this. Its look like i have some trouble on recursively flat map the child and grand child array.

let result = [
  {
    parent_id: 1,
    child_id: 3,
    grand_child_id: 5,
  },
  {
    parent_id: 1,
    child_id: 3,
    grand_child_id: 6,
  },
  {
    parent_id: 2,
    child_id: 4,
    grand_child_id: 7,
  },
  {
    parent_id: 2,
    child_id: 4,
    grand_child_id: 8,
  },
];

Solution

  • Only works for 3 levels.

      let result = [];
    
      for(let firstParent of data){
            let { parent_id, child = []} = firstParent;
            for(let secondParent of child){
                let  {child_id, child:grandChilds = [] } = secondParent;
                for(let grandChild of grandChilds){
                    let {grand_child_id} = grandChild;
                    result.push({
                        parent_id,
                        child_id,
                        grand_child_id
                    })
                }
            }       
      }
    
      console.log(result);