I can't modify a property of an object using a method created inside the same object. I am trying to use foreach then console.log is undefined

Viewed 23

CODE:

    let references = [
        { nombre: 'productA', priceUsd: 2200, qty: 15 },
        { nombre: "productB", priceUsd: 1500, qty: 20 },
        { nombre: "productC", priceUsd: 3000, qty: 7 }
      ];
    const store = {
    products: references,
    increasePrice: function(percToAdd) {
    return this.products.forEach(item =>item['priceUsd']=item.priceUsd*(1+percToAdd/100));}
    }
    const increased = store.increasePrice(30);
    console.log(increased)

OUTPUT:

undefined

But I am looking for something like this:

[
{ nombre: 'productA', priceUsd: 2860, qty: 15 },
{ nombre: "productB", priceUsd: 1950, qty: 20 },
{ nombre: "productC", pricesUsd: 3900, qty: 7 }
]

I Tried the code outside the method and it works but when I put it inside a function it does not work anymore.

1 Answers

This is because forEach doesnot return value(modify the array) instead perform certain operation on each element of array.

You can use map for this case .


let references = [
    { nombre: 'productA', priceUsd: 2200, qty: 15 },
    { nombre: "productB", priceUsd: 1500, qty: 20 },
    { nombre: "productC", priceUsd: 3000, qty: 7 }
];
const store = {
    products: references,
    increasePrice: function (percToAdd) {
        return this.products.map(item => ({ ...item, ["priceUsd"]: item.priceUsd * (1 + percToAdd / 100) }));
    }
}
const increased = store.increasePrice(30);
console.log(increased)

Also you have misspelled priceUsd in last item of references.

Related