0

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);
4
  • 1
    quiz_records in the JSON is an array. You cannot direct access id with res['quiz_records'].id. Commented Oct 19, 2021 at 4:05
  • What is the workaround? Commented Oct 19, 2021 at 4:17
  • Does this answer your question? Angular 11 -Array map in ts Commented Oct 19, 2021 at 4:18
  • 1
    Nope I can't seem to find the workaround there. Commented Oct 19, 2021 at 4:22

3 Answers 3

1

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));
});
Sign up to request clarification or add additional context in comments.

Comments

1

Below code will work----

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.