如何使用 .map 和 .find 合并两个数组,避免迭代两次

问题描述 投票:0回答:1

我下面有两个数组。我正在尝试根据 customerLOB.code 匹配合并条件数组。问题是,我将结果添加了两次,因为循环迭代了两次。我怎样才能避免这种情况。非常感谢任何帮助。

这里基于 customerLOB 代码,如果匹配,我尝试获取一个包含条件列表的数组(两个数组中的对象数组)。但我得到的不是 3 个结果,而是 6 个结果。

const array1 = [
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A1",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A2",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A3",
    },
  },
];

const array2 = [
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A1",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A2",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A3",
    },
  },
];

const finalList = [];

array1.map((retrieveCondition) => {
  array2.find((item) => {
    if (retrieveCondition.customerLOB.code === item.customerLOB.code) {
      finalList.push([
        ...retrieveCondition.conditions,
        ...item.conditions,
      ]);
    }
  });
});

console.log(finalList);

angular dictionary filter foreach find
1个回答
0
投票

您正在将数组推送到数组,这不是您想要的。相反,您希望将两个对象合并为一个对象。因此,您应该使用

[...]
,而不是
{...}
。更新代码:

const array1 = [
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A1",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A2",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A3",
    },
  },
];

const array2 = [
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A1",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A2",
    },
  },
  {
    conditions: [
      {
        name: "xxx",
        id: "1",
      },
    ],
    customerLOB: {
      code: "A3",
    },
  },
];

const finalList = [];

array1.map((retrieveCondition) => {
  array2.find((item) => {
    if (retrieveCondition.customerLOB.code === item.customerLOB.code) {
      finalList.push({
        ...retrieveCondition.conditions,
        ...item.conditions,
      });
    }
  });
});

console.log(finalList);

© www.soinside.com 2019 - 2024. All rights reserved.