Using AngularJS to extract values from deeply nested JSON structures

I'm currently navigating through a nested JSON object and I'm facing challenges in accessing the sub items within it.

Below is a snippet of the JSON file I'm working with. It has successfully passed the JSONLint test, so it should be in proper format.

JSON

[{
    "fleetcheckitemid": "1",
    "checkitemdesc": "Engine oil level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "2",
    "checkitemdesc": "Water level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "3",
    "checkitemdesc": "Brake fluid level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}]

I can successfully retrieve the "fleetcheckitemid" and "checkitemdesc", but I'm encountering difficulties with accessing the "answers" values.

In my controller, I have the following code. However, I am encountering an error as soon as I try to iterate through the inner .each() loop: "TypeError: Cannot read property 'length' of undefined"

app.js

$http.get("http://mymadeupdomain/api/getfleetchecks.php?fleetid=" + $scope.newFleetIDValue).success(function(data) 
{
    $scope.data = data;
    console.log("$scope.data: " + $scope.data); // SUCCESS - [object Object], ... [object Object] 

    $scope.answersArray = [];
    console.log("$scope.answers: " + $scope.answers); // EMPTY ARRAY - NOT INITIALIZED YET 

    // Unable to access sub-items (answers) here
    $.each($scope.data, function(index, element)
    {
       var itemDescription = element.checkitemdesc; 
       console.log("itemDescription: " + itemDescription); // SUCCESS - Engine Oil Level

       var fleetcheckitemid = element.fleetcheckitemid; 
       console.log("fleetcheckitemid: " + fleetcheckitemid); // SUCCESS - 1....34

        $.each(this.answers, function(index, element)
        {
            var answers = element.answers;

            var fleetcheckid = element.fleetcheckid;
            console.log("element.fleetcheckid: " + element.fleetcheckid); // NOT WORKING
            console.log("fleetcheckid: " + fleetcheckid); // NOT WORKING
        });
    });   
});

What am I doing wrong in this code snippet? Could the [] brackets surrounding the answers in the JSON be the cause of this issue?

Answer №1

alternate solution to your query.

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
  
  $scope.data = [{
    "fleetcheckitemid": "1",
    "checkitemdesc": "Engine oil level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "2",
    "checkitemdesc": "Water level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "3",
    "checkitemdesc": "Brake fluid level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}];
  
  angular.forEach($scope.data,function(value,key){
      console.log(value.fleetcheckitemid);
      console.log(value.checkitemdesc);
        angular.forEach(value.answers,function(v,k){
            console.log(v.fleetcheckid);
             console.log(v.checkvaluedesc);
          });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">

   
</div>

Answer №2

Make sure to iterate through the $scope.answers array with a for loop instead of using this.answers. Also, remember to rename the second parameter of the $.each function to avoid conflicts with the outer element variable. This way, when the control enters a function,

$.each($scope.answers, function(index, ele) {//change the variable here too
   var answers = element.answers;
   var fleetcheckid = element.fleetcheckid;
   console.log("element.fleetcheckid: " + element.fleetcheckid);
   console.log("fleetcheckid: " + fleetcheckid); // NOT WORKING
}

If you're still unsure about how the values are being filled in $scope.answers, it's worth investigating further.

Answer №3

 const iterateData = ($scope.data) => {
       for (let data1 of $scope.data) {
           console.log("fleetcheckitemid: " + data1.fleetcheckitemid); // SUCCESS - 1....34

            for (let data2 of data1.answers) {
                console.log("element.fleetcheckid: " + data2.fleetcheckid); // NOT FUNCTIONING
                console.log("DESC: " + data2.checkvaluedesc); // NOT FUNCTIONING
            }
        }
    }

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

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

Divide a collection of q promises into batches and execute them sequentially

In order to achieve my objective of copying files while limiting the number of files copied in parallel based on a defined variable, I decided to divide an array of promises using calls to fs.copy into packets. These packets are then executed in series by ...

JSF Ajax call: Invoking a JavaScript function at the completion

Working on a project with JSF 2.0, here is the form being used: <h:form id="fff" onsubmit="reloadMap();"> <h:selectOneMenu value="#{rentCarPoolBean.state}"> <f:selectItems value="#{rentCarPoolBean.stateList}" id="stateList" /> ...

Learning the process of using JavaScript to extract data from a JSON file containing arrays

Currently grappling with the challenge of reading a JSON file using JavaScript. Unsure if my JSON file is in the correct format with arrays, but here is what I have. [ { "passageNumber":"2.3.1", "title":"Inside and out: A bronze ...

What is the best way to showcase two div elements side by side within my carousel

/* Implementing slideshow functionality */ var currentIndex = 0; displaySlides(); function displaySlides() { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); for (i = 0; i ...

Ensuring that the initial column of a table remains in place while scrolling horizontally

Thank you for taking the time to read this. I am currently working on a table within a div container (div0) where the data is dynamically generated, resulting in a table with unpredictable height and width. The outer div allows for both vertical and horizo ...

Transforming the image by encoding it to a base64 string using PHP, then including it in a JSON response, decoding it back to an image, and presenting it in

I've been working on a PHP code that fetches an image from a database and encodes it in JSON using base64. Below is the snippet of the code: $query=mysql_query("SELECT Id,Image FROM $table_first"); while ($row=mysql_fetch_assoc($query)) { $ ...

Is there a way to shuffle a DataMapper collection and then transform it into JSON format?

My frustration levels are soaring as I attempt to create a random photo JSON feed using DataMapper/Sinatra. Here's what I've managed to put together so far.. Photo.favorites.to_json(:methods => [:foo, :bar]) Everything seems to be working we ...

Remove the list by conducting a comparison analysis

<html> <head> <title> Manipulating List Items Using JavaScript </title> <script type="text/javascript"> function appendNewNode(){ if(!document.getElementById) return; var newlisttext = document.changeform.newlist.val ...

Tips for implementing collapsible mobile navigation in Django with the help of Materialize CSS

I'm facing some issues with implementing a responsive navbar that collapses into a 'hamburger bar' on mobile devices and in split view. I have managed to display the hamburger bar, but when I click on it nothing happens. Here's my curre ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...

Obtain additional information to address concerns related to onZoom and onPan issues on the line

Attempting to enhance my Chart.js line chart by fetching more data or utilizing cached backup data during onZoom/onPan events has proven quite challenging. The original code base is too intricate to share entirely, but I will outline the approaches I have ...

What is the best way to showcase information from an external API in react js?

As I develop my new app, I am integrating API data from . This feature will enable users to search for their favorite cocktail drinks and display the drink name fetched from the API on the page. However, I am encountering an error that says "Uncaught TypeE ...

Ensure NodeJS/JSDom waits for complete rendering before performing scraping operations

I am currently facing an issue with scraping data from a website that requires login credentials. When I try to do this using JSDom/NodeJS, the results are inconsistent compared to using a web browser like Firefox. Specifically, I am unable to locate the l ...

Every time I restart VSCode, I have to re-run the .zsh_profile command in order for the NVM packages to work properly

Many others have encountered a similar issue, but I'm struggling to resolve it. Every time I open VSCode, I find myself needing to run these commands in the terminal for npx, npm, and nvm to work: export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] ...

Tips for synchronizing the bounding box rotation and dimensions of a fabric group with its objects

https://i.sstatic.net/L5VNg.png Current version of fabricjs is 4.2.0 In the image provided, you can see a Text and Rectangle grouped together, both of which are rotated. It seems logical that the Bounding Box of the group should also be rotated according ...

How can you enable the sortable feature with a mousedown event instead of a drag event by utilizing Jquery UI Sortable?

I have implemented the Jquery UI Sortable plugin to enable re-ordering of table rows. Currently, the drag and drop functionality is working well, but I would like to trigger the sortable feature using a mousedown event instead of a drag event. You can vi ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...

Delete local data storage in Angular 2 upon closing the window

After the user logs in, I store their token in local storage so that it is accessible across all tabs. However, I need to remove this token from local storage when the user closes the browser or window. What is the best way to clear local storage upon clo ...