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

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

Local working fine but encountering issues on Openshift, specifically with syncing npm package versions across environments (local and global)

As I develop a forum using Angular that connects with Node/Mongo, there are numerous requests required to populate the page with necessary data. While everything functions flawlessly locally, once uploaded to Openshift, the site displays various bugs and f ...

Even with manual installation, the npm package still encounters dependency errors

Having trouble implementing the Imgur package from NPM into my Angular web app. The installation and import seemed to go smoothly, but when initializing a variable with the package, I encounter compile errors pointing to missing dependencies like 'cry ...

Switching between multiple images using Jquery on a click event

Hi there, I am currently working on a project where I need to use jQuery to switch between three images when clicked. Once the third image is clicked, it should cycle back to the first picture. I was wondering if there is a way to modify the code below so ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...

Creating unique appbars for different sections on my sidebar in ReactJs

I am trying to implement a responsive drawer and AppBar using material-ui (@material-ui/core). My goal is to display a specific AppBar for each section of the drawer. For instance, when the user navigates to the Timetable section, I want the AppBar label t ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake. Oddly enough, my if/else statement isn't working correctly - it only executes the code within the ...

Learn how to dynamically modify the text and color of a column value within a <v-data-table> component in Vue.js 2.6.11 and Vuetify 2.2.11 based on a specific condition

In my current project where I am developing a web application using ASP.NET CORE for the backend and vue.js for the frontend, I encountered an issue with Vuetify's CRUD Datatable UI Component in a page named "Category". The problem arises when trying ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

Achieving data synchronization and sequencing with AngularJS promises at a 1:1 ratio

Concern I am facing challenges with AngularJS promise synchronization and sequencing as my app expands across multiple controllers and services. In this scenario, I have an articles controller named ArticleController along with a related service named Art ...

Changing the Displayed Content with a Simple Click of a Link

Layout Overview In the process of developing a tool to streamline work tasks, I want to ensure that I am following best practices. My goal is for the website to initially display only column A, with subsequent columns generated upon clicking links in the ...

What could be the reason for the undefined value of my ID retrieved from the next JS router.query upon page refresh?

When using the id obtained from the next router.query to dynamically render elements, it works fine when accessing the room from next/link. However, upon refreshing the page, an error is thrown. https://i.stack.imgur.com/yEjGS.png Below is the code snipp ...

The convergence of Phoenix, Json, and Unix Timestamps

Currently, I am in the process of exporting data from SQL Server in json format to be able to import it into my Phoenix app. One aspect that I'm uncertain about is how to handle dates. As of now, I am exporting dates as Unix timestamps. Below is an ex ...

Preventing file overwriting using fs.writefile method

Encountering an issue where the data being saved from a chat room built with socket.io in nodejs is constantly overwritten upon submission of a message. The desired outcome is to append both the username and message to the JSON file as an object, rather th ...

What are some tips for efficiently troubleshooting a JQuery GET request to MailChimp 3.0 servers?

I am encountering an issue while trying to include users' emails in my Mailchimp 3.0 audience list. I am making a GET request using JQuery, but I keep running into the following error: {"type":"http://developer.mailchimp.com/documentation/mailchimp/g ...