合并基于Key ID的json对象,然后使用javascript将concat应用于其他碰撞键

时间:2015-05-22 09:43:33

标签: json

使用基于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"
    }
]

1 个答案:

答案 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"
  }
]