3 回答
TA贡献1876条经验 获得超5个赞
您可以在map() 中使用find( )来查找元素。即使它们在两个数组中的索引不同,这也会找到该元素。
然后使用filter()过滤undefined如果没有匹配将出现的任何值。
var arrNames = [
{name: "A"},
{name: "B"},
{name: "C"}
];
var arrInfo = [
{name: "A", info: "AAA"},
{name: "B", info: "BBB"},
{name: "C", info: "ccc"}
];
let result = arrNames.map(x => {
item = arrInfo.find(item => item.name === x.name);
if (item) {
return item.info;
}
}).filter(item => item !== undefined); // Can also use filter(item => item);
console.log(result);
TA贡献1804条经验 获得超2个赞
let result = [];
arrNames = [
{name: "A"},
{name: "B"},
{name: "C"},
]
arrInfo = [
{name: "A", info: "AAA"},
{name: "B", info: "BBB"},
{name: "C", info: "ccc"},
]
result = arrNames.map(function(_, index){
if(arrNames[index].name === arrInfo[index].name) {
return arrInfo[index].info
}
})
TA贡献1874条经验 获得超12个赞
您可以使用带有条件的地图
el.name === arrNames[index].name && el.info
方法:
if (el.name === arrNames[index].name) return el.info
let arrNames = [{
name: "A"
}, {
name: "B"
}, {
name: "C"
}]
let arrInfo = [{
name: "A",
info: "AAA"
}, {
name: "B",
info: "BBB"
}, {
name: "C",
info: "ccc"
}]
const res = arrInfo.map((el, index) => el.name === arrNames[index].name && el.info)
console.log(res)
添加回答
举报