Search code examples
angularhttp-post

How to handle nested array response form API in angular


How to handle following API response in Angular.

{ key: "some_value", testData: Array(3)}


Solution

  • Question -

    How to parse a response in an Angular application.

    Answer -

    Parsing a response can be done with JavaScript. You have an array within your example data so you need to loop through it. Each index other than the array can be accessed without a loop.

    Example -

       const response = { key: "some_value", testData: [1, 2, 3,]};
    
    // Returns the key which is not in the array
       console.log(response.key)
    
    // returns the data in the array
        response.testData.forEach((c, i, a) => {
            // Do stuff with this current index
           console.log(c);
        });
    

    Additional Information -

    Keep in mind that your example data is a JavaScript Object. Typically an API repsonse will be JSON or XML. In your case, make sure you know if you are working with a JSON Oject or a JavaScript Object.

    If the response is JSON, before using the code above convert the response.

    Converting both directions.

    JSON -> Object

    JSON.parse(response);
    

    Object -> JSON

    JSON.stringify(response)