0

How do I output the child array correctly?

   const arr = [
    [{ id: 0, parrentId: null, title: "Main tab", parrent: true }],
    [{ id: 1, parrentId: 0, title: "Main child 1", parrent: false }],
    [{ id: 2, parrentId: 0, title: "Main child 2", parrent: false }],
    [{ id: 3, parrentId: 2, title: "Main tab 2", parrent: true }],
    [{ id: 4, parrentId: 3, title: "Main child tab 2", parrent: false }]
  ];

How to output arrays according to child > parrent? But so that the id is parrentId === id

Main tab:
  1) Main child 1
  2) Main child 2
     1) Main tab 2
        1)Main child tab 2

I'm trying to

if (arr) {
    const child = arr.filter(({ hasChild }) => hasChild);
    const notChild = arr.filter(({ hasChild }) => !hasChild);

    const test = { ...child, notChild };
    console.log(test);
}
reactchel
  • 146
  • 1
  • 2
  • 10

1 Answers1

0

If I understood correctly, maybe it is something like this:


const arr = [
   [{ id: 0, parentId: null, title: "Main tab", parent: true }],
   [{ id: 1, parentId: 0, title: "Main child 1", parent: false }],
   [{ id: 2, parentId: 0, title: "Main child 2", parent: false }],
   [{ id: 3, parentId: 2, title: "Main tab 2", parent: true }],
   [{ id: 4, parentId: 3, title: "Main child tab 2", parent: false }]
];

arr.reduce((acc, data) => {

   if(data[0].parent) {

     acc = acc.concat(data[0]);
   
   } else {

     acc = acc.map(ac => {
     
       if(ac.id === data[0].parentId) {

        return {
         ...ac,
         child: ac.child ? ac.child.concat(data[0]) : [].concat(data[0])
        };

       } else {

         return ac;

       }

     });

   }

   return acc;

}, []);

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rodolfo Rangel
  • 596
  • 1
  • 3
  • 15