Home > Enterprise >  Flatten multi dimension array object to one dimensional array object
Flatten multi dimension array object to one dimensional array object

Time:01-19

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,
  },
];

CodePudding user response:

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);

CodePudding user response:

i finally got some function to solve my problem, i`m using flatMap() lodash to achieve this. thanks :)

function getChild(n) {
    let children = n.child.map((el) => {
        return { child_id: el.child_id, child: el.child };
    })[0];

    return _.map(children.child, function (item) {
        return {
            parent_id: n.parent_id,
            child_id: children.child_id,
            grand_child_id: item.grand_child_id,
        };
    });
}

console.log(_.flatMap(data, getChild));
  • Related