【问题标题】:How can I combine 2 objects and merge arrays inside of them [duplicate]如何组合 2 个对象并在其中合并数组 [重复]
【发布时间】:2019-12-20 11:03:56
【问题描述】:

我有几个具有相同属性的对象。我想组合所有具有相同第一级键值的对象。我知道传播运算符

    const obj3 = {...obj1, ...obj2}

但问题是,对象内的数组被覆盖而不是合并。

{
  "id": 1,
  "name": "firstLevel",
  "visible": true,
  "subCategories": [
    {
      "id": 2,
      "name": "secondLevel",
      "visible": true,
      "skills": [
        {
          "name": "foo",
          "id": 5,
          "visible": true
        }
      ]
    }
  ]
}
{
  "id": 1,
  "name": "firstLevel",
  "visible": true,
  "subCategories": [
    {
      "id": 2,
      "name": "secondLevel",
      "visible": true,
      "skills": [
        {
          "name": "bar",
          "id": 1,
          "visible": true
        }
      ]
    }
  ]
}

我希望这些对象可以这样组合:

{
  "id": 1,
  "name": "firstLevel",
  "visible": true,
  "subCategories": [
    {
      "id": 2,
      "name": "secondLevel",
      "visible": true,
      "skills": [
        {
          "name": "foo",
          "id": 5,
          "visible": true
        },
        {
          "name": "bar",
          "id": 1,
          "visible": true
        }
      ]
    }
  ]
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您正在寻找lodash.mergeWith,它递归地合并数组和普通对象属性。

    var object = {
      'a': [{ 'b': 2 }, { 'd': 4 }]
    };
     
    var other = {
      'a': [{ 'c': 3 }, { 'e': 5 }]
    };
    
    function customizer(objValue, srcValue) {
      if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
      }
    }
     
    _.mergeWith(object, other, customizer);
    // => { 'a': [{ 'b': 2 }, { 'c': 3 }, { 'd': 4 }, { 'e': 5 }] }
    

    对于您知道对象 ID 的特定情况,此定制器功能将起作用as requested

    function customizer(objValue, srcValue) {
      if (_.isArray(objValue)) {
        for (const srcItem of srcValue) {
          const objItem = objValue.filter(item => item.id === srcItem.id);
          if (objItem.length) {
            objValue = objValue.map(item => {
              if (item.id === objItem[0].id) {
                return _.mergeWith(item, srcItem, customizer);
              }
    
              return item;
            });
          } else {
            objValue = [...objValue, srcItem];
          }
        }
    
        return objValue;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 2019-07-15
      • 1970-01-01
      相关资源
      最近更新 更多