Home > Blockchain >  replace two for loop with find or filter method - javascript
replace two for loop with find or filter method - javascript

Time:10-12

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?

CodePudding user response:

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 }));

CodePudding user response:

@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

  • Related