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

Utilize Angular to transform items in a nested array into comma-delimited values prior to assigning them to a grid

Here is an excerpt from a JSON response retrieved from an API: { "totalCount": 2, "customAttributes": [ { "objectType": "OWNER", "atrributeId" ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...

Row in Internet Explorer 7

I have a function that reveals hidden rows in a table, which works perfectly in all tested browsers except for IE7. The function is written using Prototype.js. function showInactives(){ var row_list = $$('tr.inactive'); var ck =$('inactive_ ...

What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

How can I transmit a pong frame using WebSocket in javascript/NodeJS?

I am struggling to locate a proper example demonstrating how to send a PONG response using javascript/NodeJS within the context of a WebSocket connection (back to a server that requests it after sending a PING request). Can anyone provide guidance on thi ...

Setting the iDisplayLength property in jQuery Datatables to -1 will display all rows in the table

Using jQuery Datatables, I am trying to populate a table with entries from a server via ajax. The data retrieval works perfectly, and I am able to display them in the table. However, I am facing an issue where I want to show all rows/entries at once. I hav ...

What is the best way to convert an array to JSON in Swift?

I am having trouble extracting the value "maxtemp_c" from a JSON request. This is my attempt so far, but I keep encountering issues when trying to parse the JSON data and end up with a nil value: //I have the URL of the json let url = URL(string: "http:/ ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Is There a Quicker Alternative to Eval for Generating Deep Clones?

I am looking to create deep clones of a very large object called veryBigObject. To initialize veryBigObject, it first needs to be initialized using the initVeryBigObject function. Here is how this process looks: initVeryBigObject = function(){ veryBig ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

Experiencing 429 Too Many Requests error on Angular 7 while attempting to perform multiple file uploads

Whenever I attempt to upload a large number of files simultaneously, I encounter an issue. The API interface only allows for the submission of one file at a time, requiring me to call the service for each individual file. Currently, my code looks like thi ...

React MUI: Dynamic and Adaptive sidebar

I'm currently working on integrating React Material UI: Persistent + Responsive drawer to create a responsive layout for mobile devices with a persistent drawer for larger screens. I've come across some code that almost fits my requirements, but ...

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

Using JSON in Android to Load Data and Display in a ListView

I've encountered an issue with the following code that is meant to read a JSON file and display it in a listview - it's returning an empty list. Any advice would be greatly appreciated. Thanks! eventList.json: { "events": [ { "event": "Taste o ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

Clarifying the O365 REST API

I am currently trying to figure out what I am doing incorrectly. My goal is to retrieve all contacts from O365 in either XML or JSON format, so I began my research and discovered that Microsoft offers an API that can provide the data in JSON format (excell ...