[英]How to return from a function with an array loop and nested forEach loop?
[英]How do I return array data from a foreach loop in Angular
我正在遍歷嵌套對象以獲取一些數據。 這是可行的,但我似乎無法返回數據並在其他地方使用它。
我已經嘗試過將循環作為一個承諾,但也無濟於事。 我究竟做錯了什么?
data: any = {
'1234': {
url: 'https://example1.com/',
path: 'uploads',
link: 'https://example1.com/uploads',
},
'5678': {
url: 'https://example2.com/',
path: 'uploads',
link: 'https://example2.com/uploads',
}
}
onSubmit(formData) {
this.formdata = formData;
Object.keys(this.data).forEach(key => {
if (key == this.formdata.pin) {
const url = this.data[key].url;
// have also tried this.url to no avail
}
});
// says undefined
console.log(url);
// set up headers, etc...
// I need to use here
this.http.post(url, body, head)
...
}
onSubmit(formData) {
this.formdata = formData;
let url; // Define here so that its accessible
Object.keys(this.data).forEach(key => {
if (key === this.formdata.pin) {
url = this.data[key].url;
// have also tried this.url to no avail
}
});
// Now url is in scope
console.log(url);
...
}
將forEach
切換到map
可以簡化此過程; map
返回值,而forEach
則不。
舊:
Object.keys(this.data).forEach(key => {
if (key == this.formdata.pin) {
const url = this.data[key].url;
}
});
// says undefined
console.log(url);
新增內容:(根據下面的評論,我還在此處添加了===
)
const urls = Object.keys(this.data).map(key => {
if (key === this.formdata.pin) {
return this.data[key].url;
// have also tried this.url to no avail
}
});
console.log(urls);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.