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

Rendering child components in Vue.js with access to parent data

I have a main component in Vue.js with the following structure: <template> <ul class="list-group"> <li class="list-group-item" v-for="item in items"> <div class="row"> <div class="col-md-6"> ...

Looking for similar arrays from two sets of multidimensional arrays

Greetings! I have the following two multidimensional arrays: Array ( [user_attempts] => 0 [2] => Array ( [0] => 1 [1] => 4 ) [3] => Array ( [0] => 32 [1 ...

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...

Oops! An error has occurred: The requested method 'val' cannot be called on an undefined object

I am struggling with this issue. This is the code that I am currently working on: http://jsfiddle.net/arunpjohny/Jfdbz/ $(function () { var lastQuery = null, lastResult = null, // new! autocomplete, processLocation = function ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

Leveraging an array of Elasticsearch documents using AngularJS

The query results are given below... { "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 45, "max_score": 0, "hits": [] }, "aggregations": { ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

Having difficulty deserializing JSON data to a Xamarin ListView

Recently, I've started delving into Xamarin and exploring the use of JSON in my projects. Currently, I am fetching data from our ERP system through a REST API, which is working smoothly so far. However, I'm facing difficulty in correctly popula ...

"Troubleshooting the issue of jQuery failing to set data

Although it seems straightforward, I am puzzled as to why this code is not functioning properly. The selector is accurate, but for some reason the .faqContent div is not being updated with the data-height attribute. $('.faqItem .faqContent').eac ...

Converting a two dimensional array to a three dimensional array in PHP using a specific key value

Currently, I am working with an array. $majorEarning = array( array( 'user_id' => 1, 'booking_id' => 2, 'price' =&g ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Creating a dynamic loader with JavaScript and PHP: A step-by-step guide

Currently focused on PHP development, my task involves retrieving data from a database using multiple queries. The database may contain anywhere from 10 records to 10,000 records. I am looking for a way to incorporate a progress bar that displays the com ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

Making AJAX requests to retrieve data from a JSON database array, then utilizing the CSS visibility property to conceal HTML elements dynamically

As a enthusiastic beginner, I'm facing a challenge that seems to have no easy solution. Can someone please assist me with this: How can I assign all the ids from a JSON database to the variable dotContainer, in order to hide all corresponding HTML id ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

Issues with the functionality of the jQuery UI datepicker arise following a body replacement

Currently, I am working on a project that involves updating the page content via ajax by replacing the entire body. However, I have encountered an issue with using the jQuery datepicker in this scenario. The datepicker functionality works fine until the co ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

The issue with AngularJS ng-show and $timeout functionality not functioning as expected

As a newcomer to AngularJS, I recently started an individual project utilizing ng-show and if else statements with $timeout. Despite my efforts, I have been unable to make the answers timeout after being displayed for a few seconds. I've tried various ...

What is the best way to utilize props and mounted() in NuxtJS together?

I'm a beginner with NuxtJS and I'm looking to implement window.addEventListener on a specific component within my page. However, I also need to ensure that the event is removed when the page changes. In React, I would typically approach this as ...

Unpacking key-value pairs from a JSON array in PHP and restructuring the data

Looking for suggestions on how to transform the JSON structure shown below: $jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"}, {"Level":"399.2023%","Product":"Coffee","Temperature":"34"}, {"Level":"109.2023%","Product ...