使用Underscore平面映射和投影数组

时间:2014-04-22 11:23:16

标签: javascript arrays underscore.js

如何将具有父子关系的对象数组展平为单个数组,该数组是使用Underscore的每个父对象和子对象的乘积?假设如下:

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'}]}
]

我需要以下输出:

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'}}
]

我觉得我需要使用mapchaining

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以将每个父级映射到子级数组,然后将其展平以获取父级+子级列表:

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();

演示http://jsfiddle.net/nikoshr/8HAVJ/