我想合并两个对象数组。键是相同的,但值可能并不总是相同。
任何解决方案最好在javascript中受到欢迎,但python解决方案也很好。
以下是示例数据:
var g= [
{ id: 36, name: 'AAA', goal: 'yes' , 'random':27},
{ id: 40, name: 'BBB', goal: 'yes' },
{ id: 39, name: 'JJJ', goal: 'yes' },
{ id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];
var c= [
{ id: 36, name: 'AAA', goal: 'yes', color:"purple" },
{ id: 40, name: 'BBB', circle: 'yes', color:"purple" },
{ id: 100, name: 'JJJ', circle: 'yes'} ];
我的预期输出应该是:
var finalData = [{
{ id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
{ id: 40, name: 'BBB', circle: 'yes', color:"purple"},
{ id: 39, name: 'JJJ', goal: 'yes' },
{ id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
{ id: 100, name: 'JJJ', circle: 'yes' }
}]
这是我当前的代码,它在某种程度上起作用,但它不会添加它可能错过的键。
var finalData = [];
for(var i in g){
var shared = false;
for (var j in c)
if (c[j].name == g[i].name) {
shared = true;
break;
}
if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c);
finalData
您可以使用Map
将相同的id
保存在同一个对象中,使用Object.assign
创建独立的对象。
var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
map = new Map,
result = g.concat(c).reduce(function (r, o) {
var temp;
if (map.has(o.id)) {
Object.assign(map.get(o.id), o);
} else {
temp = Object.assign({}, o);
map.set(temp.id, temp);
r.push(temp);
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
版本没有减少和没有concat。
function merge(o) {
var temp;
if (map.has(o.id)) {
Object.assign(map.get(o.id), o);
return;
}
temp = Object.assign({}, o);
map.set(temp.id, temp);
result.push(temp);
}
var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
map = new Map,
result = [];
[g, c].forEach(function (a) {
a.forEach(merge);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这是一个Python解决方案。这会修改g
,你可能想要也可能不想要。
c_by_id = {d['id']: d for d in c}
for item in g:
item.update(c_by_id.get(item['id']), {})
这可以通过下划线函数_.uniq
和_.union
轻松实现。
只要用这个:
var finalData = _.uniq(_.union(c, g), function (ele) {
return ele.id
})
这将返回您正在寻找的东西。