Iterate through a local storage object using JavaScript's looping mechanism

I am currently working on a project to create a shopping cart using local storage. I have initialized the local storage with the following code:

var cart = {};
 cart.products = [];
 localStorage.setItem('cart', JSON.stringify(cart));

I then use AJAX to retrieve product details from an array and add them to the cart upon clicking a button event:

var product = {};
    product.id = msg.produto.id;
    product.name = msg.produto.nome;
    product.price = msg.produto.preco;
    product.image = msg.produto.name;

    addToCart(product);

The 'addToCart' function appends the product to the existing products in the local storage object using .push:

var cart = JSON.parse(localStorage.getItem('cart'));
 cart.products.push(product);

Next, I need to iterate through all the products stored in the local storage and display their details on the HTML page using either a for loop or $.each method in JavaScript:

I attempted the following approach:

localStorage.setItem('cart', JSON.stringify(cart));

var retrievedData = localStorage.getItem("cart");

$.each(retrievedData , function (i, item) {

 alert(item.nome);
 alert(item.product.nome);

});

However, this approach did not work as expected.

The data retrieved from

var retrievedData = localStorage.getItem("cart");
looks like the following:

{"products":
    [
        {
        "id":"01",
        "name":"Product Name 01",
        "price":"Product Price 01",
        "image":"Product Image 01"
        },
        {
        "id":"02",
        "name":"Product Name 02",
        "price":"Product Price 02",
        "image":"Product Image 02"
        }
    ]
}

Answer №1

Expect an array from the localStorage data containing the "products" property value of the returned object.

To achieve this, consider using:

$.each(retrievedData.products , function (i, item) {
  ...
});

Answer №2

const storedCartData = localStorage.getItem("cart");

storedCartData will hold a JSON as a string. You must first parse it to convert it into an object, using the method JSON.parse.

After that, you can refer to techniques described in Access / process (nested) objects, arrays or JSON to explore the data structure.

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

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

Is it possible to restrict the application of jquery .css() to a particular media query only?

Whenever a user's browser width is below 1160px, a media query is set up to hide my website's right sidebar. They can bring it back by clicking on an arrow icon, causing it to overlap the content with absolute positioning. To achieve this functi ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Adding and adjusting the size of different DIV elements within a shared area

Looking to create a dynamic bar with the ability to add multiple child DIVs (similar to this: https://i.stack.imgur.com/tdWsq.jpg). Utilizing jQuery, jQuery UI, Bootstrap, and various plugins. The structure for the div (or span) system could be structured ...

Limiting the amount of blogs shown on a single page can be achieved with Yii 1 and PHP

I have successfully implemented a feature to display blogs on one page. However, I now want to modify it so that only 5 blogs are shown per page and the user can click on a "next page" button to view the next set of 5 blogs. Here is the code snippet from ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

Inserting duplicate rows from CSV using JavaScript

Currently, I am utilizing Papaparse to sum up rows with duplicate SKUs in my CSV file. I'm striving to achieve this task without the use of additional JS libraries such as D3. Here is a snippet of how my CSV data is structured: SKU,Daily total,Weekly ...

Is it necessary to sanitize input fields manually in Angular 6?

Is it necessary for me to manually sanitize all user inputs, or does Angular handle this process automatically? In my login form, the data is sent to the server upon submission. Do I need to explicitly sanitize the data, or does Angular take care of sanit ...

Learn how to extract information from the Australian Bureau of Statistics by utilizing pandasmdx

Has anyone successfully retrieved ABS data using the pandasdmx library? Below is an example code that retrieves data from the European Central Bank (ECB) and works as expected. from pandasdmx import Request ecb = Request('ECB') flow_response ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Retrieve a specified quantity of JSON data from an external API

Dealing with a recently received API from an external source: (please note: the data returned is extensive) I'm aware that I can retrieve this large object by using the following method: $.getJSON('https://www.saferproducts.gov/RestWebServices ...

"Exploring the depths of PHP: Generating a JSON string from an array

I am trying to work with PHP code in an Object-Oriented manner and the values I am getting are objects. However, I need to convert these O.O.P objects into JSON data for use by JavaScript. So, I converted my objects into arrays on the PHP end, but when I t ...

When attempting to make an HTTP POST request from an Android device to a PHP server,

After attempting multiple tutorials on the internet, I am struggling to successfully make a simple HTTPRequest to a PHP script for user registration. The code I have tried is resulting in a NullPointerException when using HTTP POST and showing null values ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

How can I extract data from Google Calculator using Json in a Windows Phone 7 app written in C#

Currently in the process of developing a WP7 application that involves implementing a currency exchange functionality. Although I could use CSV for this purpose, I've encountered limitations in the C# Silverlight libraries whenever I attempt to work w ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

The process of filtering JSON data in Angular can be easily achieved by utilizing the filter functionality

Seeking recommendations for useful books or online resources to learn how to filter JSON data effectively using angular filters. Interested in tackling more complex datasets. Any assistance on this matter would be greatly appreciated. ...