为什么map函数返回undefined但console.log注销?

时间:2019-01-03 16:20:02

标签: javascript

我想返回两个对象数组的匹配属性。但是我没有从map函数定义。

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

3 个答案:

答案 0 :(得分:0)

您要执行的操作是:

/* first we filter fruits1 (arbitrary) */
let matchingFruits = fruits1.filter(f1 => {
  /* then we filter the frut if it exists in frtuis2 */
  return fruits2.find(f2 => f2.name === f1.name)
}).map(fruit => fruit.name) // and now we map if we only want the name strings

如果您不使用polyfill Array.find,则在IE中将无法使用。另一种方法是使用Array.indexOf(感谢您指出@JakobE)。

请注意,Array.forEach return valueundefined,并且为了正确地正确使用Array.map,我们必须以某种方式使用返回的值或将其分配给变量,刚刚对matchingFruits做过。

答案 1 :(得分:0)

您正在寻找的是数组交集

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

答案 2 :(得分:0)

您可以使用Set并过滤名称。

const names = ({ name }) => name;

var 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" }],
    fruits2 = [{ id: 7, name: "pear" }, { id: 10, name: "avocado" }, { id: 5, name: "pineapple" }],
    common = fruits1
        .map(names)
        .filter(Set.prototype.has, new Set(fruits2.map(names)));

console.log(common);