【问题标题】:merge json data from the same array合并来自同一个数组的 json 数据
【发布时间】:2015-12-20 13:07:27
【问题描述】:

我有一个这样的 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() 不是正确的方法,因为它只会覆盖键中最后提供的值。

在显示上处理好还是在数据显示前处理好?

问候

【问题讨论】:

    标签: javascript jquery arrays json


    【解决方案1】:

    您可以使用 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);
    

    【讨论】:

    • 那么如果我除了id还有其他的key,我会在这部分一一插入? (memo[item.id] = memo[item.id] || {id: item.id, otherKey1 : otherValue1, otherKey2 : otherValue2, ... , otherKeyN : otherValueN, branch: []}) ?还是有别的办法?
    • 好的,通过添加其他键,我现在使用 $.extend()。 $.extend( memo[item.id], item);
    【解决方案2】:

    尝试使用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>

    【讨论】:

      猜你喜欢
      • 2018-07-01
      • 2021-05-18
      • 2019-06-09
      • 1970-01-01
      • 2015-05-07
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      相关资源
      最近更新 更多