javascript - 为什么map函数返回未定义但console.log注销?
问题描述
我想返回两个对象数组的匹配属性。但是我从地图函数中得到了未定义。
let fruits1 = [
{id: 1, name: "apple"},
{id: 2, name: "dragon fruit"},
{id: 3, name: "banana"},
{id: 4, name: "kiwi"},
{id: 5, name: "pineapple"},
{id: 6, name: "watermelon"},
{id: 7, name: "pear"},
]
let fruits2 = [
{id: 7, name: "pear"},
{id: 10, name: "avocado"},
{id: 5, name: "pineapple"},
]
fruits1.forEach((fruit1) => {
fruits2.filter((fruit2) => {
return fruit1.name === fruit2.name;
}).map((newFruit) => {
//console.log(newFruit.name);
return newFruit.name;
})
})
解决方案
你要找的是一个数组交集:
// Generic helper function that can be used for the three operations:
const operation = (list1, list2, isUnion = false) =>
list1.filter( a => isUnion === list2.some( b => a.name === b.name ) );
// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
inFirstOnly = operation,
inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);
用法:
console.log('inBoth:', inBoth(list1, list2));
工作示例:
// Generic helper function that can be used for the three operations:
const operation = (list1, list2, isUnion = false) =>
list1.filter( a => isUnion === list2.some( b => a.name === b.name ) );
// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
inFirstOnly = operation,
inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);
let fruits1 = [
{id: 1, name: "apple"},
{id: 2, name: "dragon fruit"},
{id: 3, name: "banana"},
{id: 4, name: "kiwi"},
{id: 5, name: "pineapple"},
{id: 6, name: "watermelon"},
{id: 7, name: "pear"},
]
let fruits2 = [
{id: 7, name: "pear"},
{id: 10, name: "avocado"},
{id: 5, name: "pineapple"},
]
console.log('inBoth:', inBoth(fruits1, fruits2));
推荐阅读
- r - 最新的 gganimate:如何在后台有一个固定的情节?
- javascript - 如何使用 ReactJS 在动态表上显示每一行的价格?
- c# - Timer C#中的匿名函数
- postgresql - jooq、postgres 以及从多表更新和返回数据失败
- javascript - Javascript >>>" 到 PHP
- html - html 无法正确放置元素
- javascript - 使用 Malsup Ajax 表单提交后重定向到另一个操作
- angular - Angular PWA 应用程序基本问题
- sql - 按子句分组,我是否必须调用我在 Select 中使用的所有行?
- python - 有没有办法使用 python Telegram-Bot 获取个人资料图片更新?