我需要通过公共ID合并多个json对象。我的问题是我的对象有不同的ID密钥。
var object1 = [
{ "name":"apples" ,"w": 1, "x": 2 },
{ "name":"banana" ,"w": 1, "x": 2 },
{ "name":"cherry" ,"w": 1, "x": 2 },
];
var object2 = [
{ "type":"banana" ,"y": 3, "x": 4 },
{ "type":"cherry" ,"y": 3, "x": 4 },
];
我想获得:
var object1 = [
{ "name":"apples" ,"w": 1, "x": 2 },
{ "name":"banana" ,"w": 1, "x": 4, "y": 3 },
{ "name":"cherry" ,"w": 1, "x": 4, "y": 3 },
];
我想使用相同的Array [object1]而不是创建一个新的。 我创建了一个codepen here
答案 0 :(得分:2)
循环浏览object2
并使用Array.prototype.find
更新水果 - 请参阅下面的演示:
var object1 = [{ "name":"apples" ,"w": 1, "x": 2 },{ "name":"banana" ,"w": 1, "x": 2 },{ "name":"cherry" ,"w": 1, "x": 2 }];
var object2 = [{ "type":"banana" ,"y": 3, "x": 4 },{"type":"cherry" ,"y": 3, "x": 4 }];
object2.forEach(function(e){
var found = object1.find(function(k){
return k.name === e.type;
});
if(found) {
found.x = e.x;
found.y = e.y;
}
});
console.log(object1);

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

答案 1 :(得分:2)
您可以使用reduce()
创建新数组,并查找相同类型的object2
对象中是否存在具有相同名称的对象。
var object1 = [
{ "name":"apples" ,"w": 1, "x": 2 },
{ "name":"banana" ,"w": 1, "x": 2 },
{ "name":"cherry" ,"w": 1, "x": 2 },
];
var object2 = [
{ "type":"banana" ,"y": 3, "x": 4 },
{ "type":"cherry" ,"y": 3, "x": 4 },
];
var result = object1.reduce(function(r, e) {
var o = object2.find(a => e.name == a.type);
r.push(o ? Object.assign({}, e, {x: o.x, y: o.y}) : e);
return r;
}, [])
console.log(result)
答案 2 :(得分:0)
我为你的问题找到了解决方案,你能试试吗?
var object1 = [
{ "name":"apples" ,"w": 1, "x": 2 },
{ "name":"banana" ,"w": 1, "x": 2 },
{ "name":"cherry" ,"w": 1, "x": 2 },
];
var object2 = [
{ "type":"banana" ,"y": 3, "x": 4 },
{ "type":"cherry" ,"y": 3, "x": 4 },
];
function mergeObject(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
function mergeObjectInArray(firstArray, firstArrayKey, secondaryArray, secondaryArrayKey) {
var resultArray = new Array();
for(var firstArrayIndex in firstArray) {
var firstArrayObject = firstArray[firstArrayIndex];
var resultArrayObject = firstArrayObject;
for(var secondaryArrayIndex in secondaryArray) {
var secondaryArrayObject = secondaryArray[secondaryArrayIndex];
if(firstArrayObject[firstArrayKey] === secondaryArrayObject[secondaryArrayKey]) {
resultArrayObject = mergeObject(firstArrayObject,secondaryArrayObject);
delete resultArrayObject[secondaryArrayKey];
}
}
resultArray.push(resultArrayObject);
}
return resultArray;
}
var resultArray = mergeObjectInArray(object1, "name", object2, "type");
// Assuming JSON.stringify - not available in IE<8
console.log(JSON.stringify( resultArray ) );
&#13;