簡體   English   中英

為什么map函數返回undefined但console.log注銷?

[英]Why does map function return undefined but console.log logs out?

我想返回兩個對象數組的匹配屬性。 但是我從地圖功能得到未定義。

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

您要做的是:

/* 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返回值undefined並且為了正確地實際使用Array.map ,必須像我們對matchingFruits一樣,以某種方式使用返回值或將其分配給變量。

您正在尋找的是數組交集

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

您可以使用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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM