Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!