6

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

6
  • You have holes in array Commented Sep 10, 2015 at 8:42
  • possible duplicate of What is the most efficient method to groupby on a javascript array of objects? Commented Sep 10, 2015 at 8:42
  • @Andreas underscore vs Vanilla Javascript. This is not duplicate Commented Sep 10, 2015 at 8:42
  • @Tushar It's a question about grouping an object with different approaches/solutions (including some libraries and maybe focussed on performance but this won't hurt A.Qua I think). Commented Sep 10, 2015 at 8:46
  • Can you give a real example of the expected result? Commented Sep 10, 2015 at 8:47

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.