我有两个数组:
var a = [
{aId: 1, name: "a1"},
{aId: 2, name: "a2"}
];
var b = [
{parentId: 1, description: "b1"},
{parentId: 1, description: "b2"},
{parentId: 2, description: "b3"}
];
我想根据parentId === aId;
合并这些数组我做了:
var c = _.map(a, function(obj) {
return _.assign(obj, _.find(b, {parentId: obj.aId}));
})
这可以按预期工作,但我需要它来处理重复项 - 当找到匹配项时,它会正确合并它,但我需要它将合并推送到新属性,而不是合并。
我得到了什么:
[
{aId: 1, name: "a1", description: "b1"},
{aId: 2, name: "a2", description: "b3"}
]
我想要的是什么:
[
{
aId: 1,
name: "a1",
b: [
{parentId: 1, description: "b1"},
{parentId: 1, description: "b2"}
]
},
{
aId: 2,
name: "a2",
b: [
{parentId: 2, description: "b1"}
]
}
]
当然可以省略共同财产;
答案 0 :(得分:2)
你的代码差不多完成了;在_.assign()中,您可以传递属性b
等于_.filter()而不是_.find()的对象:
{
b: _.filter(b, {parentId: obj.aId})
}
请注意_.find()返回匹配的元素,否则为undefined,_.filter()返回新的已过滤数组。
代码:
var a = [{aId: 1, name: "a1"}, {aId: 2, name: "a2"}],
b = [{parentId: 1, description: "b1"}, {parentId: 1, description: "b2"}, {parentId: 2, description: "b3"}];
_.map(a, function(obj) {
return _.assign(obj, {
b: _.filter(b, {parentId: obj.aId})
});
});
console.log(a);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;