user1720275
user1720275

Reputation: 57

Underscore.js New Array of Objects with child arrays

I have an array of objects in the following structure

var projects = [
    {id:'1',name:'project1', parentid:"null"},
    {id:'2',name:'project2', parentid:"null"},
    {id:'3',name:'subproject1', parentid:"1"},
    {id:'4',name:'subproject2', parentid:"1"},
    {id:'5',name:'subproject3', parentid:"2"}
];

I would like to make a new array with the following structure

var newProjects = [
    {text:'project1', children:[
        {id:'3',name:'subproject1', parentid:"1"},
        {id:'4',name:'subproject2', parentid:"1"}
    ]},
    {text:'project2', children:[
        {id:'5',name:'subproject3', parentid:"2"}
    ]}
]

I have been able to do this using a bunch of loops and if statements but would like to clean it up by using Underscore.js but been unable to do so. could someone please point me in the right direction?

Upvotes: 0

Views: 560

Answers (1)

Aaron Hinni
Aaron Hinni

Reputation: 14716

Based on the data given, you can probably get away with using a simple groupBy and map.

Something like this:

var grouped = _.groupBy(projects, 'parentid');
var newProjects = _.map(grouped['null'], function (project, id) {
    return {
        text: project.name,
        children: grouped[project.id]
    };
});

If you have deeper nesting, you'll need to work out a more robust solution, but this should give you an idea on what to do.

Upvotes: 1

Related Questions