Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method:

localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}]));

When I inspect it, this is how it appears:

imageSource: "http://127.0.0.1:5500/allproductIMG/cake1.png"
productPrice: 490
productQuantity: "5"
productTitle: "Hazelnut Praline Cake"

Now, when I try to retrieve the "productTitle" from JSON, I use the following method:

let productdata = JSON.parse(localStorage.getItem('orderproduct'));

'orderproduct' is the variable where the data is stored. However, when I check the productTitle using console.log:

console.log("The product title is"+ productdata.productTitle);

The result shows that 'productTitle' is undefined. Why is this happening? How can I retrieve the value "Hazelnut Praline Cake" instead of "undefined"

Answer №1

Make sure to properly handle the array before trying to access the nested object,

console.log("The product title is"+ productdata[0].productTitle);

If not, you can simply store it without using an array

localStorage.setItem('orderproduct', JSON.stringify({imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}))

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

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Exploring Pandas capabilities with complex nested JSON structures

I have this specific dataset that includes the following information: {'Result': { 'j': {'confirmed': true, 'version': '1'}, 'z': {'confirmed': false, &a ...

A guide to adding a picture to AWS S3 with the help of GraphQL

When trying to upload a base64 string via GraphQL, I encountered an issue. It seems that if the string exceeds 50,000 characters, GraphQL fails to reach the resolve function without giving any error messages. However, when the string is less than 50,000 ...

What is the method to exhibit the outcome of a promise on a web page within a React component?

In my search for information about promises, I have noticed that most articles provide examples using console.log. However, I am faced with a different scenario. I am working with AWS Athena and I need to display the result on a webpage in my React export. ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Updating user interface dynamically based on the most recent data stream is crucial for a seamless user experience

I am facing a challenge where I need to update the indicator in the user interface based on real-time data. The requirement is that if there has been no data received in the last 30 seconds, the indicator should turn red. However, if data is received withi ...

How to locate the index.js file within my application using Node.js?

Directory Structure bin - main.js lib - javascript files... models - javascript files... node_modules - folders and files public - index.html route - javascript files... index.js package.json I am using Express and angular.js. The ser ...

Implement a feature to dynamically load data as the user scrolls up, similar to the

I am in the process of creating a messaging platform and I am looking to implement a functionality where chat history is displayed upon scrolling up, similar to Facebook's chat system. Can anyone offer assistance with this task? ...

Just a quick inquiry regarding adding new line characters in JSON to be used in

After encountering an issue with a JSON file in my JavaScript application where it would not print new lines when viewed on the console, I am at a loss for a solution. The contents of my JSON file are as follows: [ { "id": "71046" ...

Send nodejs express static request over to secure https server

Is there a way to ensure all HTTP requests, including those for static files, are redirected to HTTPS? This is the code I currently have: app.use(express.static(__dirname + '/public')); app.get('*', function(req, res) { if (!req. ...

What is the reason for not being able to locate the controller of the necessary directive within AngularJS?

A couple of angularjs directives were written, with one being nested inside the other. Here are the scripts for the directives: module.directive('foo', [ '$log', function($log) { return { restrict: 'E', r ...

What is the reason onbeforeunload does not fire requests in Safari browser?

Is there a way to ensure that data is saved to the database when a user interacts with the page and also when they refresh it? I have tried using onbeforeunload event, but Safari does not wait for the server request to finish before reloading the page, c ...

Exploring the Node.js view object within a function and delving into the reasons why a property of

As a beginner in programming, I am seeking tips on how to effectively learn node.js. Currently, I am utilizing the "Learning Behavior Driven Development with JavaScript" book for my learning journey. I would greatly appreciate any advice on how to view ob ...

What is causing the disparity between the JSON generated using the `Factory` and the one received from the `API`?

When I use my mock stub, the escaping works properly, but with the API response, the escaping does not seem to be applied for some reason. Here is a snippet of my Mock stub factory. require 'faker' F ...

Dealing with Large JSON Strings in ASP.NET MVC Views

Large JSON Objects (approximately 1.5 MB) are received in Controller C1. They are then converted to strings and stored in a hidden label in View V1. The JSON data in V1 is utilized by parsing it in JavaScript J1. An occurrence of Out of Memory Excepti ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...

Nodejs asynchronous tasks are not functioning correctly with SetInterval

I'm a newcomer to the world of Node.js. I've set up a simple asynchronous task that needs to run every 10 minutes. The setInterval function should trigger at regular intervals as specified, updating the value for the variable api key. I can' ...

Obtaining an array from a printed array using PHP

Recently I've been working with PHP and wrote a script that outputs an array. Here's an example of how the result looks like: Array ( [0] => Array( [timestamp] => 1390242176 [length] => 32 ...

Creating three-dimensional text in Three.js

My script is based on this documentation and this resource. Here is an excerpt of my code: <script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script> <script> var text = "my text", height = 20 ...