How to handle javascript and json file processing?

My json data structure is as follows:

var json = {
  "A": {
    "A1": {
      "A11": "A",
      "A12": "B",
      "A13": "C"
    },
    "A2": {
      "A21": "A",
      "A22": "B",
      "A23": "C"
    }
  },
  "B": {
    "B1": {
      "B11": "A",
      "B12": "B",
      "B13": "C"
    },
    "B2": {
      "B21": "A",
      "B22": "B",
      "B23": "C"
    }
  }
}

To access a specific element in the json, you can use:

json.B.B13

If you are looking to loop through all objects (A, B), you can achieve this by using a for loop. Here's an example of how you can do it:

I initially tried using for(...) and json[0].B13 but that approach did not work. Can anyone provide guidance on how to accomplish this task?

Answer №1

In order to handle nested objects, you can implement recursion and use console.log to display key-value pairs. If the value is an object, continue iterating through its properties:

const data = {A:{A1:{A11:"A",A12:"B",A13:"C"},A2:{A21:"A",A22:"B",A23:"C"}},B:{B1:{B11:"A",B12:"B",B13:"C"},B2:{B21:"A",B22:"B",B23:"C"}}};

const iterateNestedObjects = ([key, value]) => {
  if (typeof value === 'object' && value !== null)
    Object.entries(value).forEach(iterateNestedObjects)
  else
    console.log(key, value)
}

Object.entries(data).forEach(iterateNestedObjects)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* this is not relevant */

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

Combining the functionality of a click event

Is it possible to combine these two functions in a way that ensures when '#css-menu' is shown, '.menu' becomes active, and vice versa? $('.menu').click(function() { $('#css-menu').toggleClass('shown hidden& ...

Challenges faced with react-bootstrap-autosuggest

After spending the entire day attempting to integrate the package from here into my create-react-app project upon ejection, I encountered the following error: Failed to compile. Error in ./~/react-bootstrap-autosuggest/lib/Autosuggest.js Module not found ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Unable to establish API connection in node.js

As a novice, I recently delved into the world of APIs using node.js. My goal was to fetch data from a simple API for practice. This venture is just an experiment and any assistance or guidance on connecting to APIs, especially those requiring an API key, ...

How can I position an object in Three.js to perfectly align with the left half of the screen, adjusting both its width

When the button is clicked, I want the entire 3D object's width and height to adjust to fit on the left side of the screen, while displaying a div HTML info on the right side. How can I make the object fit on the left side of the screen? Can I use ma ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

Angular renders HTML elements

Greetings! I am currently experimenting with using AngularJS for the frontend and Wordpress as the backend of my project. To load content from Wordpress into Angular, I am utilizing a JSON wordpress plugin along with making $http requests. The content th ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Enhance the functionality of Jackson's JsonParser

My current software applications have the capability to read a JSON configuration like this: { "a": 5, "b": 3 } And convert it into a POJO structure as shown below: public class AddConf { private Number a; private Number b; public int add() ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...

Capturing screenshots with Selenium in Node.js is proving to be quite sluggish

My current project involves using Selenium with Mocha in Node.js for UI testing on a website. I want to capture screenshots after each test to review and share the results visually. The challenge arises when there are AJAX calls and JavaScript animations ...

Tips on extracting data from an API using jQuery

Struggling with parsing data and feeling a bit stuck. That's why I'm reaching out for assistance. This is where I need help: How do I specifically retrieve market_cap values? Each value needs to be accessed individually for a specific string I ...

Implementing a functionality in Angular.js to automatically populate an input field when a checkbox is checked

My goal is to set the respective input field to a specific value when a checkbox is checked. Below is an example of what I am trying to achieve. <label class="checkbox-inline"> <input type="checkbox" name="favoriteColors"> Five </label& ...

Arrow indicating the correct direction to expand or collapse all items with a single click

I have successfully implemented the "expand/collapse all" function, but I am facing an issue with the arrow direction. The arrows are not pointing in the correct direction as desired. Since I am unsure how to fix this problem, I have left it empty in my co ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

Error when accessing JSON property in Angular with Ionic 2: A Strange TypeError

I have implemented a provider in my Ionic project to fetch the user object from storage. Below is the code: import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class ApiProvider { ...

What is the proper way to enable the Google Analytics cookie only once another consent cookie has been set and is marked as "true"?

I am currently using React/Nextjs on my website along with the react-cookie-consent library. This setup generates a pop-up where users can agree to the cookie policy, and if they do, a CookieConsent with the value "true" is set. In addition to this, I wis ...