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

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Is it possible to execute a standalone .js file using Node.js and Express?

I am working on a Node.js/Express project and I need to test a specific file containing a single function. Currently, I have been calling this function in the index.js file and running all functions within it by using `npm run dev`. However, I would like t ...

Tips for retrieving a local variable from inside a callback and using it outside the function

Recently, I started utilizing npm plaid and I'm looking for a way to access the variable trans outside of the plaidClient.getTransactions function. Any suggestions would be greatly appreciated. var trans; var startDate = moment().subtract(30, &apo ...

Enumerating items in a JSON dataset

I am facing an issue with my JSON data structure: var data = { "conv0": { "id":"d647ed7a5f254462af0a7dc05c75817e", "channelId":"emulator", "user": { "id":"2c1c7fa3", "name":"User1" }, "co ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

React.js - Error message: onChange is not defined

My application has successfully integrated the last.fm API to fetch related artists. The concept is simple - search for an artist and receive a list of related artists in return. While using 'onClick' works flawlessly as it retrieves the input v ...

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

splitting xmlhttp.responsetext using loops

Currently, I have a JavaScript function that utilizes xmlhttp.responsetext to fetch data from MySQL. This data is then used to populate form fields in a dropdown menu, which has been functioning perfectly so far. However, the issue arises when I attempt to ...

Instead of presenting MySQL data in tables on an HTML page, showcase it in editable text boxes

I have successfully imported data from my database table into an HTML table, but now I want to display them in locked text boxes. When the user clicks an "edit" button, the corresponding text box should become unlocked so that they can edit the data and sa ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

Utilizing the output from a console.log in a webpage

Although the function I created is functioning properly and successfully outputs the value to my terminal onSubmit, I am facing difficulty in understanding why this code isn't updating my html. router.post('/index', function(req, res, next) ...

When attempting to add objects to an indexedDB object store, an InvalidStateError is encountered

I have defined IndexedDB and IDBTransaction dbVersion = 1; var db; var dbreq; var customerData = { ssn: "444", name: "Bill", age: 35, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bbbebe92b1bdbfa2b3bcabfcb1bdbf"& ...

Are the JQuery appended elements exceeding the width of the parent div?

I have an HTML div that is styled using the Bootstrap class span9. <div class="span9"> <div id = "selectedtags" class="well"> </div> <button class="btn" type="button" id="delegatecontent">Generate report</button&g ...

Another option for authorizing a document

DISCLAIMER: I am seeking information on technologies for signing a JSON document from the server-side, not recommendations for specific products or services. I want to explore the various options available for signing a JSON document, especially when mult ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...