Home > Software engineering >  Angular 11 - Array mapping undefined
Angular 11 - Array mapping undefined

Time:10-19

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Below code will work----

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

  • Related