3
我有兩個數組:Lodash合併陣列和處理重複
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 ===援助合併這些陣列;
我所做的:
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"}
]
}
]
共有財產當然可以省略;
使用'_.filter',而不是'_.find',讓你得到所有的匹配結果到一個數組中,並相應地更新你的映射。 – Shilly
謝謝,那個竅門 – Zoidy