使用基于ID的2个json对象合并,然后在其他碰撞键上应用concat ...
示例json1:
[
{
"ID": "1",
"Contents": "Hello"
},
{
"ID": "2",
"Contents": "Mushi"
}
]
示例Json 2:
[
{
"ID": "1",
"Contents": "world"
},
{
"ID": "1",
"Contents": "bye!"
},
{
"ID": "2",
"Contents": "Mushi"
}
]
合并后的预期结果:
[
{
"ID": "1",
"Contents": "Hello, world, bye!"
},
{
"ID": "2",
"Contents": "Mushi, Mushi"
}
]
答案 0 :(得分:1)
此代码snipet可以帮助您:
var arr1 = [ { "ID": "1", "Contents": "Hello" }, { "ID": "2", "Contents": "Mushi" } ];
var arr2 = [ { "ID": "1", "Contents": "world" }, { "ID": "1", "Contents": "bye!" }, { "ID": "2", "Contents": "Mushi" } ];
var result = arr1.concat(arr2).reduce(function (result, item) {
var exists = result.some(function(element) {
if(element.ID == item.ID) {
var contents = element.Contents.split(",");
contents.push(item.Contents);
element.Contents = contents.join(",");
return true;
}
});
if (!exists) {
result.push(item);
}
return result;
}, []);
结果将是
[
{
"ID": "1",
"Contents": "Hello,world,bye!"
},
{
"ID": "2",
"Contents": "Mushi,Mushi"
}
]