0

I want to convert this array:

[
         {
            "_id":"60e884adb73aa620d0583e60",
            "label":"label_1002",
            "childrens":[
               {
                  "_id":"60e88489b73aa620d0583e5f",
                  "label":"label_1001"
               }
            ]
         },
         {
            "_id":"60e88489b73aa620d0583e5f",
            "label":"label_1001",
            "childrens":[
               {
                  "_id":"60e88444b73aa620d0583e5e",
                  "label":"label_1000"
               }
            ]
         },
         {
            "_id":"60e88444b73aa620d0583e5e",
            "label":"label_1000",
            "childrens":[]
         }
]

to this and with unlimited nested childrens level:

[
      {
        _id: '60e884adb73aa620d0583e602',
        label: 'label_1002',
        childrens: [
          {
            _id: '60e88489b73aa620d0583e5f3',
            label: 'label_1001',
            childrens: [
              {
                _id: '60e88444b73aa620d0583e5e5',
                label: 'label_1000',
                childrens: []
              }
            ]
          }
        ]
      }
]

This is what I tried:

const getDescendants = async (pId) => {
   const array1 = [
     {
      _id :"60e884ceb73aa620d0583e61",
      label :"label_1003",
      childrens :[
          {
            _id :"60e884adb73aa620d0583e60",
            label :"label_1002"
           }
       ]
      },
      {
        _id :"60e884adb73aa620d0583e60",
        label :"label_1002",
        childrens :[
           {
             _id :"60e88489b73aa620d0583e5f",
             label :"label_1001"
           }
         ]
       },
       {
          _id :"60e88489b73aa620d0583e5f",
          label :"label_1001",
          childrens :[
            {
              _id :"60e88444b73aa620d0583e5e",
              label :"dechet_1000"
            }
          ]
       },
       {
          _id :"60e88444b73aa620d0583e5e",
          label :"label_1000",
          childrens :[]
       },
     ];
  let descendants = [];
  let array = [];
  let item = {
             _id: 60e884ceb73aa620d0583e61,
             label: 'label_1003',
             childrens: [
                         {
                          _id: 60e884adb73aa620d0583e60,
                          label: 'label_1002'
                         }
                 ]
        };
  let { _id, label, childrens } = item;
  array.push({ _id, label, childrens });

  while (array.length > 0) {
    let currentnode = array.pop();
    let children = array1.find(element => { return element._id === 
    currentnode.childrens[0]._id.toString()});


    children.forEach((child) => {
      let { _id, label, childrens } = child;
      descendants.push({ _id, label, childrens });
      if (child.childrens.length > 0) {
        array.push(child);
      }
    });
  }
  return descendants;
};

I want:

Nested childrens level

Dev M
  • 1,412
  • 3
  • 26
  • 46

0 Answers0