Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parent child relation sorting in javascript

I have the following structure

[
    {
         "category_id" : 1,
         "parent_category" : null
    } ,
    {
         "category_id" : 2,
         "parent_category" : 1
    },
    {
         "category_id" : 3,
         "parent_category" : 1
    },
    {
         "category_id" : 4,
         "parent_category" : 2
    },
    ,
    {
         "category_id" : 5,
         "parent_category" : null
    },
    ,
    {
         "category_id" : 6,
         "parent_category" : 5
    }


]

so I have parent children relation , I want to sort it with the following structure

[
    {
      "parent_category":[ "array of all children that follow this main parent category" ]  
    },
    {},
    {}
]

I,ve seen many solution but all of it about tree structure output

Thanks

like image 960
A.Qua Avatar asked Sep 10 '15 08:09

A.Qua


1 Answers

You can try this solution.

let json = [
    { id : 1, name : 'A', parent : 0 },
    { id : 2, name : 'B', parent : 0 },
    { id : 3, name : 'C', parent : 1 },
    { id : 4, name : 'D', parent : 2 },
    { id : 5, name : 'E', parent : 1 },
    { id : 6, name : 'F', parent : 2 },
    { id : 7, name : 'G', parent : 0 },
];

//collecting all parents (whose parent is 0)
let parents = json.filter(x => x.parent === 0);

//collecting all chlidren (whose parent is not 0)
let children = json.filter(x => x.parent !== 0);

//iterating through children and pushing it to **parents** json just below the parent
for(x of children){
    let index = parents.findIndex(obj => obj.id === x.parent);
    parents.splice(index+1, 0, x);
}

Now the parents json has the objects sorted according to parent.

parents:
   [ { id: 1, name: 'A', parent: 0 },
     { id: 5, name: 'E', parent: 1 },
     { id: 3, name: 'C', parent: 1 },
     { id: 2, name: 'B', parent: 0 },
     { id: 6, name: 'F', parent: 2 },
     { id: 4, name: 'D', parent: 2 },
     { id: 7, name: 'G', parent: 0 } ]

Hope this will help.

like image 124
Ankit Singh Avatar answered Sep 28 '22 07:09

Ankit Singh