0

I have put the data in JSON by using the setItem method:

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

and I check in the inspect is like this:

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

Now I want to get the "productTitle" from JSON, I use this method:

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

which 'orderproduct' is the variable I used to store the data. After that I use console.log to check the productTitle :

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

But, the answer shows the 'productTitle' is undefined. Why? How can I get the "Hazelnut Praline Cake" instead of "undefined"

  • What does `localStorage.getItem` return? – Anurag Srivastava Sep 12 '21 at 16:19
  • @AnuragSrivastava return the data that I have shown at the first – Kaichun Yau Sep 12 '21 at 16:22
  • Does this answer your question? [How to read an external local JSON file in JavaScript?](https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript) – Art Sep 12 '21 at 16:23
  • @ArtiomB actually no, I am not using external JSON file, but I am using the getElementById to get the value and use setItem to store them into the local storage. For example: `localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}]));` – Kaichun Yau Sep 12 '21 at 16:29

1 Answers1

0

You must destruct the array before accessing the inner object,

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

Otherwise you can save it without the array

localStorage.setItem('orderproduct', JSON.stringify({imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}))
Sam Washington
  • 626
  • 4
  • 12
  • This is the code I used to set the item: `localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}]));` Isn't it not a JSON format? – Kaichun Yau Sep 12 '21 at 16:25
  • Then the answer is you must destruct the array before accessing the inner object, updating the answer – Sam Washington Sep 12 '21 at 16:28
  • how to destruct the array first?? Sorry, I am the new beginner for JSON, I don't know how to do it – Kaichun Yau Sep 12 '21 at 16:31
  • is it updated? I am new in using stackoverflow, I am not sure whether it is updated or not – Kaichun Yau Sep 12 '21 at 16:37
  • I feel this is a single object so during saving, array can be removed and save as an object like localStorage.setItem('orderproduct', JSON.stringify({imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice})); Then you can use your original code. – Devinder Suthwal Sep 12 '21 at 16:47