映射两个数组以查看是否有 属性 匹配,然后将特定信息推送到第一个数组

Map over two arrays to see if one property matches, then push specific info into the first array

javascript 的新手,正在努力学习!我正在尝试映射两个对象数组,如果某个 属性 匹配,则将特定信息拉入第一个数组。

let result;

let arrNames = [{
  id: 10  
  name: "A"
}, {
  id: 11,
  name: "B"
}, {
  id: 12,
  name: "C"
}, }, {
  id: 13,
  name: "A"
}, {
  id: 14,
  name: "B"
}]

let arrInfo = [{
  name: "A",
  info: "AAA"
}, {
  name: "B",
  info: "BBB"
}, {
  name: "C",
  info: "CCC"
}]

如果 arrNames.name == arrInfo.name,我想将信息推送到名称数组中。

想要的结果:

let arrNames = [{
  id: 10  
  name: "A",
  info: "AAA"
}, {
  id: 11,
  name: "B",
  info: "BBB"
}, {
  id: 12,
  name: "C",
  info: "CCC"
}, }, {
  id: 13,
  name: "A",
  info: "AAA"
}, {
  id: 14,
  name: "B",
  info: "BBB"
}]

我尝试过的:

const res = arrInfo.map((el, index) => {
      if(el.name == arrNames[index].name) 
        arrNames.push(el.info)
    }

^ 这显然行不通——但我想知道 extend 或 push 在这里是否合适。

在此先感谢您的帮助(抱歉,这可能是一个骗局)。

arrInfo 转换为 Map, with the name as the key. Now map arrNames and add the info you get from arrInfoMap using the name. Use object spread 以合并两个对象:

const arrNames = [{"id":10,"name":"A"},{"id":11,"name":"B"},{"id":12,"name":"C"},{"id":13,"name":"A"},{"id":14,"name":"B"}]

const arrInfo = [{"name":"A","info":"AAA"},{"name":"B","info":"BBB"},{"name":"C","info":"CCC"}]

const arrInfoMap = new Map(arrInfo.map(o => [o.name, o]))

const result = arrNames.map(o => ({ ...o, ...arrInfoMap.get(o.name) }))

console.log(result)

你可以这样做:

let arrNames = [
  {
    id: 10,
    name: 'A'
  },
  {
    id: 11,
    name: 'B'
  },
  {
    id: 12,
    name: 'C'
  },
  {
    id: 13,
    name: 'A'
  },
  {
    id: 14,
    name: 'B'
  }
];

let arrInfo = [
  {
    name: 'A',
    info: 'AAA'
  },
  {
    name: 'B',
    info: 'BBB'
  },
  {
    name: 'C',
    info: 'CCC'
  }
];

// do this
const result = arrNames.map((item) => {
  const newItem = item; // here we define a new object that is the same as your object that is currently looped up to in your arrNames array

  // loop your second array over this currently looped to object, seeing if the name matches
  arrInfo.forEach((item2) => {
    if (item.name === item2.name) {
      newItem.info = item2.info; // if they do set a new property for your new object called info as the info from item 2 of this arrInfo array
    }
  });

  // return this new object whether or not there was a match for the name property
  return newItem; 
});

console.log(result);

所以您的 map 方法的问题是您需要记住 return 回调函数末尾的内容。您只是简单地推送到一个数组,这就像将 .map 用作 forEach。 Map 将一个数组变成另一个相同长度的数组。在这里,您正在尝试创建一个新数组,其中被循环的数组元素将有一个额外的 info 属性 如果它与您的第二个数组 arrInfo 的名称匹配。

所以你可以做的是在你的地图中使用 forEach 来检查它们是否匹配,如果匹配,添加一个新的 属性 到你的 arrayNames 元素和 return 作为你的新元素新创建的数组。希望对您有所帮助,如有需要请在评论中说明。