javascript - 如何组合 2 个对象并合并其中的数组

标签 javascript typescript

<分区>

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

    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
        }
      ]
    }
  ]
}

最佳答案

您正在寻找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;
  }
}

关于javascript - 如何组合 2 个对象并合并其中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485378/

相关文章:

javascript - 在编辑模式下对用户选择的文本进行操作

javascript - 在 Canvas 上画一个漂亮的激光(星球大战)

javascript - 查找数组的最大切片 | Javascript

html - Angular - 选择选项元素上的单击事件

Angular 8 - 在 HTML 模板中获取数据(从另一个数组内的数组内的数组)

javascript - Excel 文件通过 POST 下载 C#(避免 404.15 查询字符串错误)

javascript - 我想调用javascript函数,当选择选项(它基于for循环)仅被选择一次时

javascript - 使用纯 Javascript 或 Typescript 删除数组中的重复项

angular - Angular2 中未定义路由器

typescript - vue3 vite 别名无法按预期使用 typescript