我有一个JS对象让我们说json 1
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7"
}
.... some 100 entries
]
和json 2有点像下面
[
{
"id": "123",
"country": "USA",
"state": "KA",
"age": 24,
"group": "g1"
}
{
"id": "456",
"country": "UK",
"state": "MA",
"age": 28,
"group": "G2"
}
...... 100 entries
]
现在Id是json1和json2之间的常量,我想创建一个像下面这样的结果对象,让我们调用json3。我想匹配id并从json2获取country和state并附加到json 1.如何使用JavaScript执行此操作?
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6",
"country":"USA",
"state":"KA"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7",
"country":"UK",
"state":"MA"
}
]
答案 0 :(得分:2)
如果您使用的是jQuery,可以这样做:
var json1 = [{id:1, one: 1}, {id:2, one: 2}];
var json2 = [{id:1, two: 1}, {id:2, two: 2}];
var merged = $.map(json1, function(v1, i) {
var result = $.extend({}, v1);
var v2s = $.grep(json2, function(v2) {
return v2.id === v1.id;
});
for (var i = v2s.length - 1; i >= 0; i--) {
$.extend(result, v2s[i]);
};
return result;
});
非jQuery版本:
var merged = [];
for (var i = json1.length - 1; i >= 0; i--) {
var v1 = json1[i];
var result = {};
for (var key in v1) {
if (v1.hasOwnProperty(key)) {
result[key] = v1[key];
}
}
for (var j = json2.length - 1; j >= 0; j--) {
var v2 = json2[j];
if (v1.id === v2.id) {
for (var key in v2) {
if (v2.hasOwnProperty(key)) {
result[key] = v2[key];
}
}
}
}
merged.push(result);
};
答案 1 :(得分:1)
注意:如果你喜欢 jQuery 。
使用 $ .extend() ,您可以将一个或多个对象合并到第一个对象中。有许多方法可以使用 $。extend()来解决不同的场景。你的匹配是下面的一个,你有两个具有一些共同和不同属性的对象。由于您希望将它们合并到一个对象中,并且您还希望两个对象的所有不常见属性都存在,您需要像这样做,
var firstData = [
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6"
},
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7"
}
];
var secondData = [
{
"id": "123",
"country": "USA",
"state": "KA",
"age": 24,
"group": "g1"
},
{
"id": "456",
"country": "UK",
"state": "MA",
"age": 28,
"group": "G2"
}
];
// This will remove the properties that you don't want to be in the merged object
$.each(secondData, function(index, object){
$.each(object, function(key, value){
if(key == "age"){
delete secondData[index][key];
}
else if(key == "group"){
delete secondData[index][key];
}
});
});
// this is to merge the objects
$.extend(true, firstData, secondData);
// check your console
console.log(firstData);
.extend() 的作用是合并两个对象并将其保留在第一个对象中。第一个参数 true 指定对象将以递归方式合并。
参考文献: $.extend()