[英]array.forEach works, but not when I nest another inside
我有兩個正在處理的頁面,並且都返回一個對象數組。 當我使用以下代碼時,新結果有效:
this.adminService.waiversGetAll()
.subscribe((data: Waiver[]) => {
this.waivers = data;
this.waivers.forEach((e) => {
if(e.has_signed === true) {
e.url = `<a href="${e.signatureUrl}">View</a>`
} else {
e.url = `<a href="${e.url}">${e.message}</a>`;
}
return e;
});
console.log(this.waivers);
})
}
但是,當我嘗試對不同的數組執行相同的操作(需要更新嵌套在其中的數組的值)時,我沒有得到更新的值:
this.adminService.GetUnsignedWaivers()
.subscribe((data: Player[]) => {
console.log("data",data);
data.forEach(e => {
let record: Object = {};
for(let i = 0; i < e.waivers.length; i++) {
console.log(e.waivers[i].has_signed);
if (e.waivers[i].has_signed === true) {
e.waivers[i].url = e.waivers[i].signatureUrl;
console.log(e.waivers[i].url);
e.waivers[i].message = "View Waiver";
} else {
e.waivers[i].url = e.waivers[i].url;
e.waivers[i].message = e.waivers[i].message;
}
console.log(e.waivers[i].message);
return;
};
return e;
});
this.size = this.players.length;
console.log(this.players);
})
}
當我查看e.waivers [i] .has_signed的console.log時,數據是正確的,但是之后是不正確的。
我必須做些什么才能使這項工作? 我試過在foreach中使用for循環,以及其他一堆東西。
提供給循環的數據提供如下信息:
{
buyer: "email@someaddress.edu"
event: "COED A"
field: "Main"
net: null
player: {shirtSize: null, avp_id: 12345678, adult: true, …}
team: null
waivers: [{
email: "someemail@gmail.com",
has_signed: true,
message: "Liability Waiver",
signatureUrl: "https://somelink.pdf",
url: "https://somelink.com/somekeyidentifier"
}
如果玩家已經簽署了豁免,則將出現一個signatureUrl字段,並且消息應顯示“ View Waiver”,而不是告訴我他們將簽署哪種豁免的消息。 我希望將URL簽名時設置為signatureUrl,因此可以在不喜歡數據操作的表中使用它。
我得到的是1600條記錄,這些記錄顯示了好像每個人都沒有簽名的url,但是當我在內部循環中console.log has_signed時,應該顯示TRUE的記錄卻顯示TRUE。
快速查看它,在for
循環中有一個return
語句,這將使其在第一次迭代后停止運行。
首先,將所有return語句放入代碼中。 接下來,使用map
而不是forEach
因為前者將為您返回新的操縱數組,而后者僅用於迭代目的。
然后,您在subscribe
代碼將變為:
data.waivers = data.waivers.map((waiver) => {
if (waiver.has_signed) {
// your logic goes here...
waiver.url = waiver.signatureUrl;
waivers.message = "View Waiver";
}
// No else is required as you are just reassigning with same values
});
this.playerDetails = data;
最后,將修改后的data
綁定到模板中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.