首页 > 解决方案 > 为什么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;
    })
})

标签: javascript

解决方案


你要找的是一个数组交集

// 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)); 


推荐阅读