0

I have a question about the Javascript mapping array with an object.

cart.json:

{ "products": [ { "id": "0.17912240212736852","qty": 1 } ], "totalPrice": 336 }

Here is my code:

let cart = { products: [], totalPrice: 0 };

const a = cart.products.map(product => {
    product.id === id ? { ...product, qty: product.qty + 1 } : product;
});

// Undefined
console.log(a);

The Result I want is to add 1 to the qty

Even if I tried to do the following:

const a = cart.products.map(product => {
    console.log(product);
});

// Undefined
console.log(a);

Can any explain what is the problem? Thank you.

4
  • 1
    your arrow function isn't return anything. Use return to return the expression, or remove the function body {} to implicitly return. Commented May 22, 2020 at 9:21
  • 1
    you need to return if you use map Commented May 22, 2020 at 9:21
  • 1
    A .forEach() with a simple += 1 would be easier (unless you really need a copy of cart.products) Commented May 22, 2020 at 9:22
  • Thanks! I always forget to return when I do mapping....... I will try forEach() as well! Commented May 22, 2020 at 9:27

1 Answer 1

2

You are not returning anything, try wrapping the {} with () or directly write return,

Like this:

let cart = { products: [], totalPrice: 0 };

const a = cart.products.map(product => {
    return product.id === id ? { ...product, qty: product.qty + 1 } : product;
});

// Undefined
console.log(a);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.