Looking to loop through the JSON objects saved in an array of JSON data in local storage

I have reviewed various resources, including Iterate through nested json object array, but none of them seem to address my specific situation.

The current challenge I am facing involves storing multiple JSON objects in an array within local storage. This is necessary in case the client's form goes offline and needs to store several submissions locally. Upon reconnecting, the goal is to iterate through all the stored data in local storage and submit each JSON object as a new row into an SQL database.

Currently, I have arrays of JSON objects being stored in a local storage array. However, I'm struggling to extract each individual "{...}" object separately. Instead, I can only retrieve a single value from the array string using offlinExtractData[3] (which returns "c" from "cable_no") rather than obtaining the first JSON Object in the array containing multiple items.

For instance, a complete JSON object that will be submitted to the SQL DB looks like this before being sent to a PHP SQL file via AJAX:

{"cable_no":"90012","section_no":"1","extract_ft":"1","cable_status":"","conduit_status":"None","extract_date":"2013-09-26","extraction_team":" ","extract_notes":"1"}

While that represents one row of data, here is a snapshot of what my local storage will resemble after numerous form submissions:

[{"cable_no":"90012","section_no":"1","extract_ft":"1","cable_status":"Done","conduit_status":"None","extract_date":"2013-09-26","extraction_team":" ","extract_notes":"1"},
{"cable_no":"90012","section_no":"1","extract_ft":"2","cable_status":"Done","conduit_status":"Liner 2","extract_date":"2013-09-26","extraction_team":"E1","extract_notes":"2"},
{"cable_no":"90012","section_no":"1","extract_ft":"3","cable_status":"Done","conduit_status":"Liner 2","extract_date":"2013-09-26","extraction_team":"Unknown","extract_notes":"3"},
{"cable_no":"90012","section_no":"4","extract_ft":"4","cable_status":"Done","conduit_status":"Liner 2","extract_date":"2013-09-26","extraction_team":"Unknown","extract_notes":"4"},
{"cable_no":"90012","section_no":"1.2.3","extract_ft":"333","cable_status":"Done","conduit_status":"Liner 2","extract_date":"2013-09-26","extraction_team":"Unknown","extract_notes":"5"}]

Each {...},{...},{...} JSON Object has its unique row of data, and my objective is to return each {...} separately for submission through an AJAX function already established. How can I iterate through each object to retrieve the entire dataset instead of fragments of strings? Does that clarify my query?

Below is the code responsible for generating the aforementioned data:

//Global variables
var extractform = {
'cable_no' : "",
'section_no' : "",
'extract_ft' : "",
'cable_status' : "",
'conduit_status' : "",
'extract_date' : "",
'extraction_team' : "",
'extract_notes' : ""
}

//initially set up the store
if (!localStorage["Extract_Update"] ) {
localStorage["Extract_Update"] = JSON.stringify([]);
}
//Now return locally stored values, if set
if (localStorage["Extract_Update"]) {
var offlinExtractData = localStorage["Extract_Update"];
console.log("Array Length: " + localStorage["Extract_Update"].length + "\nParsed Data: " + offlinExtractData);
console.log(offlinExtractData[3]);
}

function update_extractform() {
$.ajax({
    type: 'POST',
    //url: './php/update_extractform.php',
    timeout: 8000, //8 seconds
    data: extractform,
    success: function(data) {
                //Save data (array) and push new data into existing web storage
                var aa = JSON.parse( localStorage["Extract_Update"] );
                console.log( aa );
                aa.push( [ extractform ] );
                localStorage["Extract_Update"] = JSON.stringify( aa );
                console.log("Submitted (offline): " + localStorage["Extract_Update"]);
}

Answer №1

If you're working with a string representation of a JSON object and need to convert it into a JavaScript object for iteration, one method is:

eval(extractJSON)[3]

In modern browsers like IE 8+, Firefox 3.1+, Safari 4+, Chrome 3+, and Opera 10.5+ (leveraging Browser-native JSON support (window.JSON)), an alternative to eval is:

JSON.parse(extractJSON)[3]

For broader compatibility, consider using an external JSON parser library like https://github.com/douglascrockford/JSON-js/blob/master/json2.js

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

The Firebase storage percentChanges() method is throwing a NaN error

I want to create a Firebase storage service using an Angular client to handle user profile image uploads. This service should return two observables: uploadProgress$ and downloadUrl$. The uploadProgress$ observable will store the value from percentChanges ...

Utilizing the <head> element in Vue.js for Injection

I am facing an issue with loading multiple EXTERNAL scripts on different pages, like Google Places Autocomplete and Facebook APIs. It doesn't make sense to load them on every route, but the documentation provides no guidance on how to handle this com ...

Uncertain about the process of upgrading this chart with the latest array modifications

My code includes a function that updates the data array with user input, which is used to create a bar graph. The issue I am facing is that while the data array in the chart gets updated upon user input, the chart itself does not. How can I ensure that the ...

Unravel the mysterious array contents

I am looking to translate array values for use in json data. The goal is to place the values in contentvalue based on the content type into json. Currently, it is displaying null. I aim to reposition the array value as $zip_num=$content->zip; based on c ...

Unable to convert JSON object to model class

I am facing an issue with deserializing JSON data into a Model class. When I try to deserialize the JSON object to a Model class data, an ERROR message is displayed: Cannot deserialize JSON object into type System.Collections.Generic.List`1[eInvoice.Mode ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Tips for resolving the error code 'ERR_REQUIRE_ESM' when working with code: to correct this issue, make sure to include the necessary library using the 'require' statement in the correct

How can I resolve this issue? I am working on an App chat project. Apologies if my language is hard to understand, as I am Thai. PS C:\Users\ADMIN\Desktop\chat\server> node server.js C:\Users\ADMIN\Desktop\ch ...

The delete function in aspx.cs never seems to be triggered from the .aspx file

I am encountering an issue with deleting items from a list, as my delete function in the .aspx.cs file is not being called. Below is my JavaScript code: function doTheDelete(doIDeleteExpenses) { if (selectedExpensesList.length > 0) { ...

How can I send an Array of parameters in JSON format to a SOAP web service?

I am trying to pass an Array of parameters to a Ksoap webservice in android using the following soap action. <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/ ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

React-Redux error: Unable to call addItem function

Recently, I started learning about redux by following an E-Commerce site tutorial that uses React and Redux. In the tutorial, there is a CollectionItem Component with a button that triggers an addItem function to add the selected item to the shopping cart. ...

An issue occurred with accessing window handles in Selenium WebDriverJS

I have encountered a similar question, but the provided answer is not working for me. Unfortunately, I do not have enough reputation to comment or request clarification on that post yet. My setup involves JavaScript, WebDriverJS, and NodeJS. The specific ...

Can someone explain why I am consistently receiving the value of undefined when accessing the file Object?

Hi there, I'm new to this so I could really use some assistance... I'm currently working on an API where only registered users can upload a card with an image of their asset for rent. In my cards.js file, I have a post request that should respo ...

Tips for identifying text within HTML code

Looking for help with this HTML code: <span class="navbar-text navbar-nav company-title">aLine</span> The text "aLine" is displayed on the navigation bar. Can you guide me on how to locate this text using xpath? ...

Jasmine - What is the best way to simulate a finally block?

After creating a controller in my test, I encountered an issue with the updateActionList function... this.createScope = function(scope) { if (scope) { this.scope = scope; } else { this.scope = $rootScope.$new(); } this.contro ...

Converting JSON File to Ruby Hash

I have a JSON file with information about different bots, including their names, parameters, and descriptions. Here's an example of how the JSON data is structured: { "csv-collector": { "parameters": { "delete_file": false, ...

I'm having trouble identifying the error in my Vue component that uses recursion. How can I pinpoint the

Currently, I am in the process of creating a questionnaire, and the JavaScript file containing the questions is a lengthy 4500 lines. Unfortunately, I am encountering a type error that is proving difficult to pinpoint within the code. Here is a link to the ...

Issue with importing Node module (@pusher/push-notifications-web) occurring when page is refreshed in Next.js

Encountering a problem while trying to integrate the node module @pusher/push-notifications-web. More information can be found at https://github.com/pusher/push-notifications-web I'm unsure whether this issue is related to Next.js or the node module ...

Techniques for determining if a file is empty using jQuery

Just starting out with JS. I want to validate the file input element before form submission using jQuery/JavaScript. I've researched various solutions, but nothing seems to be working for me. I'm trying to avoid displaying "/c/fakepath" as the ...