2 回答

TA貢獻1835條經驗 獲得超7個贊
轉換arrInfo為Map,以name為鍵?,F在映射 arrNames并添加您從arrInfoMap使用name. 使用對象展開來組合兩個對象:
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)

TA貢獻1840條經驗 獲得超5個贊
你可以這樣做:
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 方法的問題是你需要記住在你的回調函數結束時返回一些東西。您只是推送到一個數組,就像使用.mapas a 一樣forEach。Map 將一個數組轉換為另一個相同長度的數組。在這里,您正在嘗試創建一個新數組,其中被循環的數組元素將有一個額外的info屬性,如果它與您的第二個數組arrInfo的名稱相匹配。
因此,您可以做的是在地圖中使用 forEach 來檢查它們是否匹配,如果匹配,則向您的 arrayNames 元素添加一個新屬性,并將其作為新創建的數組的新元素返回。希望有所幫助,如果您需要,請在評論中要求澄清。
添加回答
舉報