用 find 或 filter 方法替换两个 for 循环 - javascript
replace two for loop with find or filter method - javascript
在我的方法中,我根据不同商店的可用性显示产品详细信息列表。为此,我正在使用这种方法。
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;
}
}
}
如何使用 find 或 filter 代替 for 循环?
结果是 prodList 的映射,内部循环执行 find 的操作,所以...
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
};
});
看起来代码将 formData.addressList
初始化为一个包含相同对象副本的数组。此分配可以作为地图中的副作用或作为第二张地图完成。
this.formData.addressList = this.detailList.map(o => ({ ...o }));
@danh 的回答应该涵盖您的循环问题。
要将 detailList 作为 addressList 添加到 this.formData,您可以使用
this.formData.append('addressList', detailList);
文档
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
在我的方法中,我根据不同商店的可用性显示产品详细信息列表。为此,我正在使用这种方法。
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;
}
}
}
如何使用 find 或 filter 代替 for 循环?
结果是 prodList 的映射,内部循环执行 find 的操作,所以...
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
};
});
看起来代码将 formData.addressList
初始化为一个包含相同对象副本的数组。此分配可以作为地图中的副作用或作为第二张地图完成。
this.formData.addressList = this.detailList.map(o => ({ ...o }));
@danh 的回答应该涵盖您的循环问题。
要将 detailList 作为 addressList 添加到 this.formData,您可以使用
this.formData.append('addressList', detailList);
文档
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append