awariat
awariat

Reputation: 382

JS Array.find if undefined element

I try to merge two arrays:

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

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

Everything works OK if in "firestoreArrayFull" there is "productSKU" with the same value like item.SELLER_SKU. But if not there is error "Cannot read property 'productSKU' of undefined" How to make condition for this situation? I would like to keep "item" only in the case of error. regards

Upvotes: 0

Views: 57

Answers (1)

Hao Wu
Hao Wu

Reputation: 20689

Looks like you have some null values in firestoreArrayFull array.

Try put y && before you make a comparison to make sure y isn't null or undefined.

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

Update

  • If not found, adds productSKU property equals to item.SELLER_SKU.
productsAll = parserArrayFull.map((item) => {
    return {
        ...item,
        ...(firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU) || { productSKU: item.SELLER_SKU }),
    };
});

Upvotes: 2

Related Questions