合并来自同一阵列的json数据

时间:2015-12-01 02:49:46

标签: javascript jquery arrays json

我有一个像这样的json数组:

    var arr1 = [
      {id : 1, branchId : 1, branchDetail : "yes"}, 
      {id : 1, branchId : 2, branchDetail : "no"}, 
      {id : 2, branchId : 1, branchDetail : "yes"}
    ];

如果数据具有相同的ID,我想合并数据,并创建另一个数据来处理合并。例如像这样:

    var finalArr = [
        {id : 1, 
         branch : [
            {branchId:1, branchDetail:"yes" },
            {branchId : 2, branchDetail : "no"}
         ]
        }, 
        {id : 2, 
         branch : [
            {branchId : 1, branchDetail : "yes"}
         ]
        }
    ];

我认为$ .extend()不是正确的方法,因为它只会覆盖密钥中最后提供的值。

在显示屏上或数据显示之前处理是否更好?

此致

2 个答案:

答案 0 :(得分:3)

您可以使用reduce,map和Object.keys执行此操作:

var arr1 = [
   {id : 1, branchId : 1, branchDetail : "yes"}, 
   {id : 1, branchId : 2, branchDetail : "no"}, 
   {id : 2, branchId : 1, branchDetail : "yes"}
 ];


var object = arr1.reduce(function(memo, item){
  // initialise item
  (memo[item.id] = memo[item.id] || {id: item.id, branch: []})

  // add the branch to it
  .branch.push({
      branchId: item.branchId, branchDetail: item.branchDetail
  });

  return memo;
},{})

var finalArray = Object.keys(object)
  .map(function(k){
    return object[k]
  })

console.log(finalArray);

答案 1 :(得分:0)

尝试使用Array.prototype.forEach()



    var arr1 = [{
      id: 1,
      branchId: 1,
      branchDetail: "yes"
    }, {
      id: 1,
      branchId: 2,
      branchDetail: "no"
    }, {
      id: 2,
      branchId: 1,
      branchDetail: "yes"
    }];

    var finalArr = [{
      id: 1,
      branch: []
    }, {
      id: 2,
      branch: []
    }];

    arr1.forEach(function(a, b, array) {
      [a]
      .forEach(function(val, key) {
        finalArr.forEach(function(obj, k) {
          if (obj.id === val.id) {
            obj.branch.push({
              branchId: val.branchId,
              branchDetail: val.branchDetail
            })
          }
        })
      })
    });

    $("pre").text(JSON.stringify(finalArr, null, 2));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<pre></pre>
&#13;
&#13;
&#13;