Pregunta

How would I flatten an array of objects with parent child relations into a single array that is a product of each parent and child object with Underscore? Assuming the following:

var parents=[
 {id:1,name:'John',children:[{id:1,name:'Nancy'},{id:2,name:'Bob'}]},
 {id:2,name:'Jack'},
 {id:3,name:'Jane',children:[{id:1,name:'Chloe'},{id:2,name:'Lisa'}]}
]

I need the following output:

var aggregate=[
 {id:1,name:'John',child:{id:1, name: 'Nancy'}},
 {id:1,name:'John',child:{id:2, name: 'Bob'}},
 {id:2,name:'jack',child:null},
 {id:1,name:'Jane',child:{id:1, name: 'Chloe'}},
 {id:1,name:'Jane',child:{id:2, name: 'Lisa'}}
]

I have a feeling that I need to use map and chaining.

Thanks in advance.

¿Fue útil?

Solución

You could map each parent to an array of children and then flatten it to obtain a list of parent+child :

var aggregate = _(parents).chain().
map(function(parent) {
    // no child case
    if ((!parent.children) || (!parent.children.length))
        return _.extend(_.omit(parent, 'children'), {child: null});

    // array of parent+child
    return _.map(parent.children, function(child) {
        return _.extend(_.omit(parent, 'children'), {child: child});
    });
}).flatten().value();

And a demo http://jsfiddle.net/nikoshr/8HAVJ/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top