【问题标题】:To merge two object in to a single. I have this array将两个对象合并为一个。我有这个数组
【发布时间】:2017-03-18 01:07:02
【问题描述】:

将两个对象合并为一个对象。我有这个数组

var input= [
  {
    code:"Abc",
    a:10
  },

  {
    code:"Abc",
    a:11
  },
  {
    code:"Abcd",
    a:11
  }
]

我需要输出为

[
  {code:"Abc",a:[10,11]},
  {code:"Abcd",a:[11]},
]

Please help

【问题讨论】:

标签: javascript object merge


【解决方案1】:
function merge(anArray){
    var i, len = anArray.length, hash = {}, result = [], obj;
    // build a hash/object with key equal to code
    for(i = 0; i < len; i++) {
        obj = anArray[i];
        if (hash[obj.code]) {
            // if key already exists than push a new value to an array
            // you can add extra check for duplicates here
            hash[obj.code].a.push(obj.a);
        } else {
            // otherwise create a new object under the key
            hash[obj.code] = {code: obj.code, a: [obj.a]}
        }
    }
    // convert a hash to an array
    for (i in hash) {
        result.push(hash[i]);
    }
    return result;
}

--

// UNIT TEST
var input= [
  {
    code:"Abc",
    a:10
  },

  {
    code:"Abc",
    a:11
  },
  {
    code:"Abcd",
    a:11
  }
];

var expected = [
  {code:"Abc",a:[10,11]},
  {code:"Abcd",a:[11]},
];

console.log("Expected to get true: ",  JSON.stringify(expected) == JSON.stringify(merge(input)));

【讨论】:

    【解决方案2】:

    您需要合并具有相同code 的对象,因此,任务很简单:

    var input = [
      {
        code:"Abc",
        a:10
      },
    
      {
        code:"Abc",
        a:11
      },
      {
        code:"Abcd",
        a:11
      }
    ];
    
    // first of all, check at the code prop
    // define a findIndexByCode Function
    function findIndexByCode(code, list) {
      
      for(var i = 0, len = list.length; i < len; i++) {
        if(list[i].code === code) {
          return i;
        }
      }
      
      return -1;
    }
    
    var result = input.reduce(function(res, curr) {
      var index = findIndexByCode(curr.code, res);
      
      // if the index is greater than -1, the item was already added and you need to update its a property
      if(index > -1) {
        // update a
        res[index].a.push(curr.a);
      } else {
        
        // otherwise push the whole object
        curr.a = [curr.a];
        res.push(curr);
      }
      
      return res;
    }, []);
    
    console.log('result', result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2017-04-24
      • 1970-01-01
      • 2017-02-04
      • 2021-07-13
      • 2018-05-24
      • 2015-10-11
      相关资源
      最近更新 更多