简体   繁体   English

Angular 11 - 数组映射未定义

[英]Angular 11 - Array mapping undefined

I'm using api to get the response array, I'm trying to map the "id" under the "quiz_records" array but it returns undefined.我正在使用 api 来获取响应数组,我试图将“id”映射到“quiz_records”数组下,但它返回未定义。 I think that my code are correct.我认为我的代码是正确的。 This is my attempt.这是我的尝试。

array大批

"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 ts

this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].id);
console.log(this.quiz_records);

quizRemarks is an array of objects containing an array of quiz_records . quizRemarks是包含的阵列对象的数组quiz_records Try this to get a flat list of ids of quiz_records :试试这个以获得quiz_records ids的平面列表:

this.quiz_records = [];
this.quizRemarks.forEach(remark => {
  this.quiz_records.push(...remark.quiz_records.map(rec => rec.id));
});

Below code will work----下面的代码将工作----

this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].map(r => r.id)); this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].map(r => r.id));

You're truing to get an id property from an array, what it inpossible.您想从数组中获取 id 属性,这是不可能的。 You can use nested map + flat() array method.您可以使用嵌套 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM