Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with:

var data = [
   {
      "country":"Andorra",
      "code":"AD",
      "state":[
         {
            "state_code":"AD1",
            "state_description":"aaAndorra1"
         },
         {
            "state_code":"AD2",
            "state_description":"aaAndorra2"
         }
      ]
   }
]

My goal is to iterate over the 'state' property and retrieve the value of the 'state_code'

This is my current approach :

for (var key in data) {
        if (data.hasOwnProperty(key)) {
            if(data[key].state.state_code === "AD1"){
                console.log(data[key].state.state_description);
        }
    }

However, I'm getting an undefined result.

Any suggestions or assistance would be greatly appreciated.

Thank you!

Answer №1

Give this code a try

for (let x = 0; x < infoList.length; x++) {
    for (let y = 0; y < infoList[x].stateInfo.length; y++) {
        if(infoList[x].stateInfo[y].abbrev === "AD1"){
            console.log(infoList[x].stateInfo[y].description)
        }
    };
};

Answer №2

Attempt to iterate starting from the outer object and display it,

data.forEach(function(country){ //Loop through countries
  country.state.forEach(state){ //Loop through states
    console.log(state.state_code,state.state_description);
  });
});

Just a reminder, avoid using for-in loop when iterating over an array. It will go through all the enumerable properties of an object including the prototypes. I noticed you used .hasOwnProperty(), which is good for preventing such issues, but in this case, using for-in loop is unnecessary.

DEMO

Answer №3

If you are looking to extract an array containing all state codes:

var result = data.reduce(function(array, item) {
    // Loop through each state in the item
    item.state.forEach(function(state){
      // Add the state_code to our resulting array
      // You can add conditions here such as 
      // if(state.state_code === "AD1") array.push(state.state_code)
      array.push(state.state_code)
    });
    return array;
}, [])

Check out this JSFiddle example

Answer №4

let peopleData = data.filter(person => person.age > 18);
peopleData.forEach(individual => {
  console.log(individual.name);
});

Answer №5

The data variable you have declared is an array of objects, each object containing an array of states. To iterate deep into this structure, your loop should be structured as shown below (successfully tested):

    for (var i = 0; i <= data.length; i++) {
        for(var j = 0; j <= data[i].state.length; j++){
            alert("Here is the state code: " + data[i].state[j].state_code);
        }
    }

Answer №6

The for...in loop is used to cycle through the enumerable properties of an object

If you need to iterate over Arrays, consider using a traditional for loop or the Array#forEach method

for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].state.length; j++) {
        if (data[i].state[j].state_code === "AD1") {
            console.log(data[i].state[j].state_description);
        }
    }
}

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

Ensure that each number is entered only once in the input field

Is there a way to use javascript/jquery to prevent a user from entering the same number twice in an input box? Users can enter multiple numbers one at a time, but I need to notify them or take action if they try to input the same number again. I attempted ...

Switching the hierarchy of list items in React

I have a JSON structure with nested elements. const JSON_TREE = { name: "PARENT_3", id: "218", parent: { name: "PARENT_2", id: "217", parent: { name: "PARENT_1", i ...

Need help addressing a sliding page issue in my Upwork clone script using JavaScript

For those familiar with Upwork's UI, you may have noticed a small feature I implemented. When a user clicks on a freelance job offer, another page opens from the left side using transform: translate(120%) to transform: translate(0). The issue arises ...

Getting the value of an HTML tag returned from an Ajax request

After making an AJAX call in VBScript, I am receiving the following HTML: <html> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td width="100%" ...

JSON.parse has thrown an unexpected token error with 'e'

Attempting to retrieve information from a JSON object stored in a file using FileReader. The contents of the json file are as follows: {"markers": [ { "point":new GLatLng(40.266044,-74.718479), "homeTeam":"Lawrence Library ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

jquery unbinding events can lead to faster performance

I'm in the process of creating a content-heavy slideshow page that heavily relies on event triggers, with about half of them utilizing the livequery plugin. I'm curious if unloading these events between slides to ensure only the active slide has ...

Display or conceal several elements using JQUERY/HTML upon hovering

Here is the current progress: <div style="position: relative;"> <a href="#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "position: a ...

Having issues with Vue.js and the splice method not functioning properly on an array row

Having an Object array, I noticed that when I try to remove an object from the array list, only items are deleted from the end. <div class="hours" v-for="(time, index) in hour" :key="index"> So, I decided to place a cli ...

Transferring information from ReactJs via the fetch API to a nodeJs server

I've encountered an issue where I am sending JSON data from my React application using the Fetch API, but on the server side, the req.body is showing up as empty. I'm not sure what the problem could be. Here is a snippet of my React code: impor ...

What is the best way to refresh or render a list in a React application?

While attempting to update the calendar days by using useState, I encountered a "too many re-renders" error. Even though the list was updated correctly, the component did not render on the screen as expected. I am struggling with figuring out how to update ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...

Creating a hierarchical JSON structure using a database query in JavaScript

Currently, I am in the process of building a nested JSON object by parsing a query string obtained from an SQL database. This constructed JSON object will then be utilized by Angular to display data in the user interface using angular2-query-builder. The ...

Problem with Bootstrap multiselect: it only opens the first time, and stops working after an ajax call

I am having trouble using Bootstrap multiselect with jQuery ajax. When I run the ajax code, the multiselect button stops working properly. To see the issue in action, click here: and look at the last multiselect dropdown. Here is the ajax code snippet: ...

Using Vue.js, is it possible to apply a class to a clicked element and then remove it when another element is clicked?

While developing an app using Vue.js, I have run into an issue. I am familiar with how to solve this problem using jQuery, but I am struggling to find a solution within my Vue app. Let me explain quickly - I have a list of items and I want to assign a spec ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

Retrieving data from a JSON provider instance

I want to streamline the following code block by eliminating the let expression feed |> Fbjson.Parse |> Seq.head |> (fun jsonFeed -> isPromotion triggerInterval jsonFeed.Data) |> getDecision Instead of using let, I would like to pipe dir ...

Top technique for creating a unique cursor image for a website

I'm looking for the most efficient way to create a custom cursor image for my CSS/HTML5 website without using Flash. Ideally, I would like to implement this using CSS rather than resorting to Javascript. If Javascript is necessary, I want to know whic ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...