[英]Angular 11 - Array mapping undefined
我正在使用 api 來獲取響應數組,我試圖將“id”映射到“quiz_records”數組下,但它返回未定義。 我認為我的代碼是正確的。 這是我的嘗試。
大批
"quizRemarks": [
{
"id": 160,
"user_id": 1,
"quiz_id": 18,
"module_id": 29,
"number_of_correct_answers": 2,
"created_at": "2021-10-15T03:52:52.000000Z",
"updated_at": "2021-10-15T03:52:52.000000Z",
"time_started": null,
"time_finished": null,
"remarks": 1,
"quiz_records": [
{
"id": 27,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "DriverPH",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What is the name of this application?"
},
{
"id": 28,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "Red",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What traffic light color tells you to stop before the intersection?"
}
]
}
]
ts
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].id);
console.log(this.quiz_records);
quizRemarks
是包含的陣列對象的數組quiz_records
。 試試這個以獲得quiz_records
ids
的平面列表:
this.quiz_records = [];
this.quizRemarks.forEach(remark => {
this.quiz_records.push(...remark.quiz_records.map(rec => rec.id));
});
下面的代碼將工作----
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].map(r => r.id));
您想從數組中獲取 id 屬性,這是不可能的。 您可以使用嵌套 map + flat()數組方法。
const result = res['quizRemarks'].map(remarks => {
return remarks['quiz_records'].map(record => record.id);
}).flat();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.