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

92
Views
replace two for loop with find or filter method - javascript

In my method, i am displaying product details list based on availability in different shops. For this, i am using this kind of approach.

for (let i = 0; i < this.prodList.length; i++) {
  let setContent = false;
  for (let j = 0; j < res.data.length; j++) {
    if (res.data[j].product === this.prodList[i].value) {
      this.detailList[i] = {
        product: this.prodList[i].value,
        content: res.data[j].content,
        shopName: res.data[j].shopName
      };
      this.formData.addressList[i] = {
        product: this.prodList[i].value,
        content: res.data[j].content,
        shopName: res.data[j].shopName
      };
      setContent = true;
      break;
    }
  }
}

How to use find or filter instead of for loop?

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

0

The result is a map of the prodList, and the inner loop does just what find does, so...

this.detailList = this.prodList.map(prod => {
  let resProd = res.data.find(r => r.product === prod.value);
  return {
    product: prod.value,
    content: resProd.content,
    shopName: resProd.shopName
  };
});

It looks like the code initializes formData.addressList to an array with copies of the same objects. This assignment could be done as a side-effect within the map or as second map.

this.formData.addressList = this.detailList.map(o => ({ ...o }));
about 4 years ago · Juan Pablo Isaza Report

0

@danh 's answer should cover your loop question.
For appending the detailList as addressList in your this.formData, you can use

this.formData.append('addressList', detailList);

Documentation
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

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!