首页 > 解决方案 > JS Array.find 如果未定义的元素

问题描述

我尝试合并两个数组:

productsAll = parserArrayFull.map((item) => {

        return {
            ...item,
            ...firestoreArrayFull.find((y) => y.productSKU === item.SELLER_SKU),
        };
    });

如果在“firestoreArrayFull”中有与 item.SELLER_SKU 具有相同值的“productSKU”,则一切正常。但如果没有错误“无法读取未定义的属性'productSKU'”如何为这种情况制定条件?我只想在出错的情况下保留“项目”。问候

标签: javascriptarrays

解决方案


看起来您在firestoreArrayFull数组中有一些空值。

在进行比较之前尝试 puty &&以确保yisnullundefined.

productsAll = parserArrayFull.map((item) => {
    return {
        ...item,
        ...firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU),
    };
});

更新

  • 如果未找到,则添加productSKU等于 的属性item.SELLER_SKU
productsAll = parserArrayFull.map((item) => {
    return {
        ...item,
        ...(firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU) || { productSKU: item.SELLER_SKU }),
    };
});

推荐阅读