简体   繁体   中英

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. 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

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 . Try this to get a flat list of ids of quiz_records :

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));

You're truing to get an id property from an array, what it inpossible. You can use nested map + flat() array method.

const result = res['quizRemarks'].map(remarks => {
  return remarks['quiz_records'].map(record => record.id);
}).flat();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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