我有两个对象数组:
var a = [{id:456, name:'sojuz'},
{id:751, name:'sputnik'},
{id:56, name:'arianne'}]
var b = [{id:751, weight:5800},
{id:456, weight:2659},
{id:56, weight:6700}]如何将数组a扩展到新的数组c,在id属性相同的数组b中添加权重属性:
var c = [{id:456, name:'sojuz', weight:2659},
{id:751, name:'sputnik', weight:5800},
{id:56, name:'arianne', weight:6700}]发布于 2015-09-21 17:49:49
这是一种使用下划线的方法:
var c = _.map(a, function(element) {
var treasure = _.findWhere(b, { id: element.id });
return _.extend(element, treasure);
});如果你想摆弄它(看看我在那里做了什么):http://jsfiddle.net/b90pyxjq/3/
发布于 2015-09-21 17:54:33
可以将列表_.map和list b中的每个索引(_.indexBy)对象映射到扩展对象(_.extend),以生成合并对象的列表。
下面的解决方案利用了Underscore.js库。
var a = [
{ id: 456, name: 'sojuz' },
{ id: 751, name: 'sputnik' },
{ id: 56, name: 'arianne' }
];
var b = [
{ id: 751, weight: 5800 },
{ id: 456, weight: 2659 },
{ id: 56, weight: 6700 }
];
function mergeLists(listA, listB, idField) {
var indexA = _.indexBy(a, idField)
var indexB = _.indexBy(b, idField);
return _.map(indexA, function(obj, key) {
return _.extend(obj, indexB[key]);
});
}
var c = mergeLists(a, b, 'id');
document.body.innerHTML = JSON.stringify(c, null, ' ');body {
white-space: pre;
font-family: monospace;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
编辑
我已经修改了上面的示例,消除了a列表不必要的索引。我的解决方案比上面的Aurélien Thieriot解运行效率更高,大约快48%。
您可以在这里看到它的作用:http://jsperf.com/underscore-merge/3
function mergeLists3(listA, listB, idField) {
var indexB = _.indexBy(listB, idField);
return _.map(listA, function(obj, key) {
return _.extend(obj, indexB[obj[idField]]);
});
}发布于 2015-09-21 17:46:46
像这样的东西可以工作,但绝对不是最优的:
var c = [];
for(var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
if(b[j].id == a[i].id) {
var newC = {
id: a[i].id,
name: a[i].name,
weight: b[j].weight
}
c.push(newC);
break;
}
}
}然而,这确实有O(n^2)的复杂性,我确信它可以被优化。
https://stackoverflow.com/questions/32701359
复制相似问题