Solving the Angular 11 issue of undefined array mapping

When using an API to retrieve a response array, I encountered an issue trying to map the "id" under the "quiz_records" array as it kept returning undefined. Despite believing that my code was correct, I couldn't figure out the problem.

Here is the snippet of the array:

"quizRemarks": [
        {
            "id": 160,
            "user_id": 1,
            "quiz_id": 18,
            "module_id": 29,
            ...
                },
                ...
            ]

This is the TypeScript code segment I attempted:

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

Answer №1

quizRemarks is a collection of objects that contain an array of quiz_records. You can use the following code snippet to extract a list of ids from the quiz_records:

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

Answer №2

Check out the following code snippet:

this.quiz_records variable is being populated with ids from the 'quizRemarks' array using Array.map method.

Answer №3

Attempting to retrieve an id property from an array may seem impossible at first. However, a solution exists by utilizing a nested map function along with the flat() method available for arrays.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the orientation of the mat-slide-toggle

Is there a way to change the direction of a mat-slide-toggle from right-to-left to left-to-right without involving the text or label position? I want the switch itself to be on the right when off and on the left when on. I have considered inverting the va ...

What is the best way to ensure that decimal numbers are shown in the right locale number format by default in an Ionic/Angular app

I am currently working on an Ionic/Angular application that frequently requires the display of decimal numbers on its pages. The LOCALE_ID in my app is set to "cs", so I expect numbers to be displayed using this locale. Ideally, "1,000.23" would display as ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Error with CUSTOM_ELEMENTS_SCHEMA in Angular unit testing

Struggling with Unit tests for a new project that requires fixing. I added the "CUSTOM_ELEMENTS_SCHEMA" to prevent Angular from deeply inspecting child components, but now I'm encountering an error that I can't quite figure out. Unexpected value ...

Converting Hexadecimal and Binary into QR Codes

Is there a way to generate a QR code from a byte array? I successfully decoded one using "zxing", but now that it has been altered, I would like to convert it back. If you know of a solution, please share it with me. Below is the code derived from "zxing": ...

Eliminate repetitive elements within an array of objects

Is there a way to eliminate duplicate values in an object array using Javascript? 0: {d: “2021/01/19”, color: “#009988"} 1: {d: “2021/01/19”, color: “#CC3311"} 2: {d: “2021/01/19”, color: “#009988"} 3: {d: “2021/01/19”, ...

Converting flat data into a nested object using JavaScript

Exploring the realms of react/ES6, I encountered an intriguing anomaly while utilizing the reduce method to convert a flat array received from an API into a nested object structure. Although I was well-versed in map and filter functions, the concept of red ...

Transform JSON data into an Array to create visual representations on a graph

Retrieving values from a MySQL database and exporting them to JSON can be done with the code snippet below: <?php require_once 'includes/global.inc.php'; $query = "SELECT * FROM `chart_sales` ORDER BY id LIMIT 0 , 100"; $result = mysql_que ...

Is there a guide available on how to run Angular IDE in Eclipse?

After installing Angular IDE for Eclipse, I am unable to locate any documentation on running an existing Angular project in Eclipse using Angular IDE. I would like to know how to initiate an 'ng serve' instance in Eclipse, deploy an application t ...

Encountered an issue while resolving dependency tree for angular tslib

When running npm install, I encountered the error shown in this image: https://i.stack.imgur.com/PInQE.png The CLI version is Angular CLI: 9.1.8. Any assistance would be greatly appreciated. Thank you! ...

Enhance Your NestJS Experience: Using Interceptors for Mapping and Error Handling

I'm looking for a NestJS interceptor that can log requests in all scenarios, including both successful executions and errors. Below is an example implementation: public intercept(context: ExecutionContext, next: CallHandler): Observable<any> { ...

Angular router link circles back to its originator

I've been working on a basic login page that transitions to a homepage once the user successfully logs in. So far, I've focused solely on the HTML structure of the login component without implementing any code in the corresponding TypeScript file ...

Utilize ngClass for every individual section

I have completed the implementation of all UI components, which are visually appealing. https://i.sstatic.net/hxJQr.png Here is the data structure I am using: public filters = [ { tag: 'Year', label: 'ye ...

Error TS2339: The property 'SOLDE' is not found in the 'AdvTitres' type

I am working with an array and need to retrieve the value of the SOLDE variable. You can find the JSON file here. When I try to access the SOLDE property, I get the following error message: error TS2339: Property 'SOLDE' does not exist on type ...

"Encountering the error message "Uncaught TypeError: $(...).summernote is not a function" while working with

I've encountered an issue while trying to implement summernote into my Angular app. I keep receiving the error message "$(...).summernote is not a function" and it seems like summernote is not loading properly on the page. I'm unsure of what step ...

Obtain elements from a nested array in JSON format

While working on HTML elements within the "Test" object, I am creating individual elements for each object. These objects can be either type:block or type:list and may contain an array named "List" when they are of type:list. I aim to generate an HTML ".p ...

Warning: The value returned by this.profileService.getUserProfile(...) does not exist

My challenge involves setting up a profile page with options to update username, password, and email. I've managed to get the "change email" and "change password" functions working smoothly. However, when I try to apply the same method to "change name ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Instructions for creating a button in Angular 6 that will only allow submission of .json files upon clicking

I am in the process of developing a new section in the app dedicated to imports. I am looking to add an import button that specifically allows for Json files only. My experience lies mostly in backend development, but I am delving into Angular 6 for this ...

Is there a method to instruct angular-cli (for angular 2) to produce a minified version of css files?

When running "ng serve" in angular-cli, the generated css is not minified as expected. Is there a specific setting to configure in angular-cli-build or an additional plugin to install? This is the content of my angular-cli-build.js file: var Angular2App ...