如果值匹配,则合并两个对象数组

如果某些值最终相等,我正在尝试使用合并值创建一个新的对象数组。

举个例子:

const arr1 = [{name: "Sven", firstName: "Alan", age: 24, profile: "Hello, i'm Alan"}, {name: "Mign", firstName: "Alex", age: 44, profile: "Hello, i'm Alex"}];

const arr2 = [{location: "Miami", alias: "ALAN", isAlive: true}, {location: "Los Angeles", alias: "Ethic", isAlive: true}]

在这种情况下,第一个数组的 firstName 与第二个数组的别名匹配,在这种情况下,我想将它们合并为对象并像这样返回它们:

const newArray = [{name: "Sven", firstName: "Alan", age: 24, profile: "Hello, i'm Alan",  isAlive: true, location: "Miami"}]

我尝试了多种解决方案,但最接近的解决方案是:

  const newArray = arr1.map((item, i) => {
    const mapping = arr2.map(sym => sym.firstName.toLowerCase());
    if (mapping.includes(item.alias.toLowerCase())) {
      return Object.assign({}, item, arr2[i]);
    }
  });

在这种情况下,我将与 object.assign 中的索引合并,因此我的解决方案不正确,一切都会混合在一起。

以上是如果值匹配,则合并两个对象数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>