Traverse through the keys and values of a JSON object using JavaScript

I have a json string that needs to be parsed in a specific way. The structure of the json is as follows:

{ "a": [{
    "b": [
        ["c"],
        []
    ], "d": [
        [],
        []
    ], "e": [
        [],
        ["f"]
    ], "g": [
        [],
        ["h", "i"]
    ]
}] }

My current code for parsing and iterating through the keys and values is not giving me the desired output. I am getting some unexpected numbers as keys, which are likely the index numbers of empty values. How can I modify this pure javascript code to only get "a,b,c,d,e,f,g,h,i" as keys and their respective values?

var jsonData = JSON.parse("name");
for (var key in jsonData) {
  if (jsonData.hasOwnProperty(key)) {
    // do stuff
  }
}

Answer №1

Here is a methodical approach to navigating the data structure. Whenever the input is an array, it will go through each element consecutively; when the input is an object, it will display each key and then delve into its corresponding value; otherwise, it will simply present the string representation of the input.

let info = { "a": [{
    "b": [
        ["c"],
        []
    ], "d": [
        [],
        []
    ], "e": [
        [],
        ["f"]
    ], "g": [
        [],
        ["h", "i"]
    ]
}] };

function explore(input) {
  if (Array.isArray(input)) {
    input.map(explore);
  } else if (typeof input === 'object') {
    Object.keys(input).forEach(key => {
      console.log(key);
      explore(input[key]);
    });
  } else {
    console.log(input);
  }
}

explore(info);

Answer №2

To find a solution similar to the one given, you may consider using a regular expression on the JSON data:

const jsonData = {
  "x": [{
    "y": [
      ["z"],
      []
    ],
    "m": [
      [],
      []
    ],
    "n": [
      [],
      ["o"]
    ],
    "p": [
      [],
      ["q", "r"]
    ]
  }]
};

const result = JSON.stringify(jsonData).match(/\w+/g);
console.log(result.join())

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

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Add an error message to my throw object within the JSON response

I need to include the error message from the JSON Response of the API in my error object {'status': response.status, 'msg': ''} if there is one, or else just throw the error object without a message. However, currently the thr ...

Maximum opacity in Three.js fog

My Current Endeavor: I am in the process of developing a lightweight GIS application with topography. One feature I want to implement is atmosphere haze. The Code I'm Working With: (Please bear with me as I have multiple scenes) fogColor = new T ...

Tips for removing the Y-Axis entirely from a CanavasJS chart

I'm working with a canvasJS chart and my goal is to completely hide the Y-Axis. I've managed to remove the Y-Axis line and title in this JSFiddle example. I came across these properties to hide the Y-Axis title and line, but I'm struggling t ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

What is the best way to utilize a component function within Vue to delete an item from an array stored in the parent's data?

It might be more helpful for you to take a look at the VueJS code related to this and then I can provide some explanation: new Vue({ el: '#app', data: { history: [ {name: 'red', value: '#f00'}, ...

Safari is not properly rendering a React/Next.js website (showing a blank page)

Recently, I've been facing a frustrating bug on my Next.js website. When I try to open it in Safari, there's a 50/50 chance that it will either load correctly or show a blank page with faint outlines of components but no text. This issue occurs o ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

What is the best way to encode only a specific section of a JavaScript object into JSON format?

Currently, I am in the process of developing a 2D gravity simulation game and I am faced with the challenge of implementing save/load functionality. The game involves storing all current planets in an array format. Each planet is depicted by a Body object ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

AngularJS ng-repeat with dynamic ng-model is a powerful feature that allows for

I am attempting to dynamically generate the ng-model directive within an ng-repeat, but I am encountering a browser error. Our goal is to dynamically retrieve attributes of a certain type and set them in the DOM. The specific error I am receiving is: Err ...

Function returning undefined when accessing prototype property in JavaScript

When attempting to create an image rotator using prototypal inheritance, I am encountering an error in the console showing: TypeError: this.curPhoto is undefined this.curPhoto.removeClass('previous'); I have placed this code in the callb ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

Utilizing Javascript to export modules and call multiple functions simultaneously

Is there a way to automate the calling of all functions within a module instead of individually selecting each one? For instance: bettermovies.js module.exports={ printAvatar: function(){ console.log("Avatar"); }, printLord: funct ...

Commencing CSS Animation Post Full Page Loading

I am looking for a solution using WordPress. In my specific case, I want the CSS Animations to take effect only after the page has completely loaded. For example: click here This is my HTML: <div class="svg-one"> <svg xmlns="ht ...

Can you explain the concept of (A == B == C) comparison in JavaScript?

Surprisingly, the comparison I expected to fail was this: var A = B = 0; if(A == B == 0) console.log(true); else console.log(false); To my surprise, it doesn't return true. What's even more astonishing is that console.log((A == B == ...

What is the best way to display the elements of an array within an HTML div element?

I've been trying to display the contents of an array in a div container on my HTML file, but I'm stuck. Here's what I currently have: function printArray() { var $container = $('.container'); $container.html(''); ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

My Angular project is experiencing issues with Socket.IO functionality

After successfully using a post method in my endpoint, I encountered an error when integrating it with socket io. The error pertained to a connection error and method not being found. Any help or source code provided would be greatly ap ...