我使用Backbone / lodash作为项目,我希望根据特定值合并2个对象数组。通过下面的示例,合并基于具有2个不同键(id和数字)的相同值。
实施例
var people = [
{
id: "1",
name: "John"
},
{
id: "2",
name: "Jane"
}
];
var data = [
{
number: "2",
role: "Designer"
},
{
number: "1",
role: "Developer"
}
];
// Outpout
var merge = [
{
id: "1",
number: "1",
name: "John",
role: "Developer"
},
{
id: "2",
number: "2",
name: "Jane",
role: "Designer"
}
];
答案 0 :(得分:3)
_.map(people, function(p){
return _.merge(
p,
_.find(data, {number: p.id})
)
})
答案 1 :(得分:2)
我不知道lodash函数完全符合这个用例。但是,您的目标可以通过纯JavaScript和lodash助手 A
和_.assign()
很好地实现:
_.values()

var people = [{id: "1", name: "John"}, {id: "2", name: "Jane"}];
var data = [{number: "2", role: "Designer"}, {number: "1", role: "Developer"}];
var resultObj = {};
people.forEach(function(item) {
resultObj[item.id] = item;
});
data.forEach(function(item) {
resultObj[item.number] = _.assign({}, resultObj[item.number], item);
});
var result = _.values(resultObj);
console.log(result);

答案 2 :(得分:1)
通过连接值对数组进行排序。
zipWith
将数组压缩在一起。
defaults
合并每个迭代的对象。
var people = [
{id: "1", name: "John"},
{id: "2", name: "Jane"}
];
var data = [
{number: "2", role: "Designer"},
{number: "1", role: "Developer"}
];
var result = _.zipWith(
_.sortBy(people, person => person.id),
_.sortBy(data, dataItem => dataItem.number),
(person, dataItem) => _.defaults(person, dataItem)
);
console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.1/lodash.min.js"></script>
&#13;
答案 3 :(得分:0)
您可以使用Array#map()来迭代所有data
并使用Array#find()设置p
所有p.id === d.number
个对象属性:
var people = [{id: "1",name: "John"}, {id: "2",name: "Jane"}],
data = [{number: "2",role: "Designer"}, {number: "1",role: "Developer"}],
merge = data.map(d => {
var p = people.find(p => p.id === d.number);
p.number = d.number;
p.role = d.role;
return p;
});
// Outpout
console.log(merge);
.as-console-wrapper { max-height: 100% !important; top: 0; }