Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys:

{
    "main": [
        {
            "Example1": [
                {
                    "Example1_Var02": "5",
                    "Example1_Var09": "443",
                    "Example1_Var27": "23",
                    "Example1_Var01": "31"
                }
            ],
            "Example2": [
                {
                    "Example2_Var99": "2",
                    "Example2_Var84": "344",
                    "Example2_Var46": "56",
                    "Example2_Var03": "78"
                }
            ]
        }
    ]
}

These key names are unknown to me and may change frequently, except for the main key. After a successful $.ajax() call that fetches this data (e.g. success: function(data) {), I want to store each nested array in local storage without having to know their specific keys. However, my attempts to do this using known sub-array keys are not working. For example:

for(var key in data){
   localStorage.setItem(key.Example1[0], JSON.stringify(data[key.Example1]));
}   

results in an error "Uncaught TypeError: Cannot read property '0' of undefined". Since I can't achieve this with known sub-array keys, I'm finding it challenging to handle this at a higher level of abstraction. How can I store all nested arrays within "main" separately in local storage even when their names are unknown in the JSON? Thank you for your assistance.

Answer №1

In the case where 'main' is always present and the object's structure remains consistent, regardless of its content, you can utilize a for...in loop to iterate through the object:

for(var outerKey in data.main){ 
    for(var innerKey in data.main[outerKey]){ 
        localStorage.setItem(innerKey, JSON.stringify(data.main[outerKey][innerKey]));
    }
}

console.log(localStorage.getItem('ExampleData'));
// "[{"Var02":"5","Var09":"443","Var27":"23","Var01":"31"}]"

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 is the technique for combining a string and an HTML element using literal values?

Trying to merge text with a hyperlink: const myText = `${t('privacyTxt')}` + `${<a>{t('privacyLink')}</a>}`; output: If you want to know more about our data processing, check out our[object Object] What else do I need ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Issue with List<Object> formatting in JSON is not working as expected

Currently, I am retrieving data from a ResultSet and storing it in a list: ResultSet resultSet = stmt.executeQuery(sql); List<Object> res = new ArrayList<>(); while(resultSet.next()){ res.add(resultSet.getObject(1)); } return res; ...

Transform JSON object into a structured JSON tree representation

I have the SQL query results stored in JSON format value = [ {"Machine": "Mach 1", "Device": "Dev a", "Identifier": "HMI 1"}, {"Machine": "Mach 1", "Device": & ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Troubleshooting why jQuery Ajax post is not sending parameters

Struggling with jQuery's $.ajax() function to send form data to an MVC route. Despite passing data, all parameters end up null in the MVC action: jQuery: $(function () { $('#signupform').submit(function (e) { e.preventDefault() ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

What is the appropriate way to incorporate a dash into an object key when working with JavaScript?

Every time I attempt to utilize a code snippet like the one below: jQuery.post("http://mywebsite.com/", { array-key: "hello" }); An error message pops up saying: Uncaught SyntaxError: Unexpected token - I have experimented with adding quotation m ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

Next.js presents a challenge with micro frontend routing

In the process of developing a micro frontend framework, I have three Next.js projects - app1, app2, and base. The role of app1 and app2 is as remote applications while base serves as the host application. Configuration for app1 in next.config.js: const ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

Capturing jQuery ajax requests in Angular

Within my Angular application, I am utilizing the integrated $.couch API from CouchDB. My goal is to intercept every ajax request, regardless of whether it originates from Angular's $http service or jQuery's $.ajax (which is utilized by $.couch). ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

Encountering difficulty in creating a Nuxt website using @googlemaps/js-api-loader

While using the @googlemaps/js-api-loader in my Nuxt 3 website, I encountered an issue. Everything worked perfectly during local development. However, when I attempted to build the project with nuxt generate (whether locally or on Vercel), I received the f ...

Instructions on opening a modal and changing the source of the iframe within the modal

I currently have a modal within my application that is triggered by Bootstrap: <div class="modal full-page fade" tabindex="-1" role="dialog" id="fullpageModal"> <div class="full-page-content"> <button type="button" class="close" d ...

When no files are uploaded, req.files.upload.length will return zero; however, if more than one file is uploaded, it will return the total number of files. In the

When using this loop, the variable “req.files.upload.length” will return the file count if 0 or more than one files are uploaded. However, it returns the file size if only one file is uploaded. Why does this happen? This is the upload handler: app.po ...

Focus on selecting the first child <li> element that contains an <a> tag within it

Struggling a bit with selecting only the first child within a li tag that contains a link. HTML: <ul class="dropdown-menu" role="menu" aria-expanded="true"> <li role="presentation" class="dropdown-header">Label</li> <li><a ...

Use PHP to create a new JSON file on the server by submitting a form, then utilize a second form to update

My current goal is to create a json file using a form and then update that file with another form. Both of these processes are handled in the process.php file. I have managed to successfully update the json file if it is named as data.json initially in pro ...