我需要结合两个json数组,由两个休息服务提供。具有相同“id”的条目属于一起。
json1 = [{id:1,name:'aaa'},
{id:5,name:'ccc'},
{id:3,name:'bbb'}
];
json2 = [{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,parameter1:'q', parameter2:'w', parameter3:'e'}
];
我需要在javascript中以下列方式组合/复制/克隆json数组(我的模型在angular2中):
json3 = [{id:3,name:'bbb',parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,name:'aaa', parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,name:'ccc', parameter1:'q', parameter2:'w', parameter3:'e'}
];
有没有办法将它们结合起来?参数名称未精确定义,需要使用可变参数向量。
我为每个循环尝试了混合。对我来说非常难看。
如果你想写它以便你可以接受任意数量的数组,而不仅仅是2,你可以使用arguments,并做这样的事情:
var json1 = [{id:1,name:'aaa'},{id:5,name:'ccc'},{id:3,name:'bbb'}];
var json2 = [{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,parameter1:'q', parameter2:'w', parameter3:'e'}
];
function joinObjects() {
var idMap = {};
// Iterate over arguments
for(var i = 0; i < arguments.length; i++) {
// Iterate over individual argument arrays (aka json1, json2)
for(var j = 0; j < arguments[i].length; j++) {
var currentID = arguments[i][j]['id'];
if(!idMap[currentID]) {
idMap[currentID] = {};
}
// Iterate over properties of objects in arrays (aka id, name, etc.)
for(key in arguments[i][j]) {
idMap[currentID][key] = arguments[i][j][key];
}
}
}
// push properties of idMap into an array
var newArray = [];
for(property in idMap) {
newArray.push(idMap[property]);
}
return newArray;
}
var json3 = joinObjects(json1, json2);
两个一线:
与lodash:
res = _(json1).concat(json2).groupBy('id').map(_.spread(_.assign)).value();
在ES2015中:
res = json2.map(x => Object.assign(x, json1.find(y => y.id == x.id)));
ES2015 georg的答案非常有用;
json1 = [
{id:1, test: 0},
{id:2, test: 0},
{id:3, test: 0},
{id:4, test: 0},
{id:5, test: 0}
];
json2 = [
{id:1, test: 1},
{id:3, test: 1},
{id:5, test: 1}
];
json1.map(x => Object.assign(x, json2.find(y => y.id == x.id)));
结果:
{id:1, test: 1},
{id:2, test: 0},
{id:3, test: 1},
{id:4, test: 0},
{id:5, test: 1}
使用嵌套循环查找相应的元素并合并它们。
for (var i = 0; i < json1.length; i++) {
var id = json1[i].id;
for (var j = 0; j < json2.length; j++) {
if (json2[j].id = id) {
for (var key in json2[j]) {
json1[i][key] = json2[j][key];
}
break;
}
}
}
最后,json1
将包含组合元素。
上面的代码假设json2
的每个元素都匹配json1
中的某些内容。如果在json2
中可以有额外的元素,那么之后你需要一个额外的循环来将它们复制到json1
。
使用forEach和过滤器我们可以解决要求。
vehicleArray1 = [{id:1, name: "a"},{id:2, name: "b"},{id:3, name:"c"}];
vehicleArray2 = [{id:1, type: "two wheeler"},{id:2, type: "four wheeler"},{id:3, type:"six wheeler"}];
var outArr = [];
vehicleArray1.forEach(function(value) {
var existing = vehicleArray2.filter(function(v, i) {
return (v.id == value.id);
});
if (existing.length) {
value.type = existing[0].type;
outArr.push(value)
} else {
value.type = '';
outArr.push(value);
}
});
console.log(outArr)
这应该为你做。我希望代码本身有意义。如果两者都存在,此示例将始终采用json1
值而不是json2
值。如果你想改变它,那么你需要在最里面的循环中切换对象引用(src[i]
和obj[j]
)。
// Will take src, and merge in the contents of obj.
// Expects an array of objects for both.
// Will keep src values in favour of obj values.
function extend(src, obj) {
// Loop the src, in this case json1
for (var i = 0; i < src.length; i++) {
// For every loop of json1, also loop json2
for (var j = 0; j < obj.length; j++) {
// If we have matching IDs operate on this pair
if (src[i].id == obj[j].id) {
// For every key in the object being merged in,
// if the key exists in src, ignore new value.
// if the doesn't exist in src, take the new value.
for (var key in obj[j]) {
src[i][key] = src[i].hasOwnProperty(key) ? src[i][key] : obj[j][key];
}
// We found our matching pair, so break out of the json2 loop
break;
}
}
}
return src;
}
// -------------------------------------------
var json1 = [{
id: 1,
name: 'aaa'
},{
id: 5,
name: 'ccc'
},{
id: 3,
name: 'bbb'
}];
var json2 = [{
id: 3,
parameter1: 'x',
parameter2: 'y',
parameter3: 'z'
},{
id: 1,
parameter1: 'u',
parameter2: 'v',
parameter3: 'w'
},{
id: 5,
parameter1: 'q',
parameter2: 'w',
parameter3: 'e'
}];
var json3 = extend(json1, json2);
// ---------------------------------------------
var pre = document.getElementById('out');
pre.innerHTML = JSON.stringify(json3);
<pre id="out"></pre>
下面是一种方法,首先构建一个由id(稀疏数组)键入的索引,以检测和组合具有匹配id值的对象,然后最终将它们连接回正常数组:
json3 = json1.concat(json2).reduce(function(index, obj) {
if (!index[obj.id]) {
index[obj.id] = obj;
} else {
for (prop in obj) {
index[obj.id][prop] = obj[prop];
}
}
return index;
}, []).filter(function(res, obj) {
return obj;
});
json1 = [
{id:1,name:'aaa'},
{id:5,name:'ccc'},
{id:3,name:'bbb'}
];
json2 = [
{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,parameter1:'q', parameter2:'w', parameter3:'e'}
];
json3 = json1.concat(json2).reduce(function(index, obj) {
if (!index[obj.id]) {
index[obj.id] = obj;
} else {
for (prop in obj) {
index[obj.id][prop] = obj[prop];
}
}
return index;
}, []).filter(function(res, obj) {
return obj;
});
document.write('<pre>', JSON.stringify(json3, null, 4), '</pre>');
如果您的浏览器支持Object.assign:
json3 = json1.concat(json2).reduce(function(index, obj) {
index[obj.id] = Object.assign({}, obj, index[obj.id]);
return index;
}, []).filter(function(res, obj) {
return obj;
});