let arr = {}; arr['0'] = '5'; arr['1'] = '4'; localStorage.setItem('arr', arr); val = localStorage.getItem('arr'); console.log(val);
If I put val = JSON.parse(localStorage.getItem('arr'));, it throws an error stating that Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at app.js:230.
arr is an object, when I stored it to localStorage, it got stored as string of [object object], how can i access the individual value of arr from localStorage.
localStorage
can only store strings, so you need to JSON.stringify
when setItem
and JSON.parse
when getItem
.
Use this while storing:
localStorage.setItem("arr", JSON.stringify(arr));
while getting:
let val = JSON.parse(localStorage.getItem('arr'))
Try this..
let arr = {};
arr['0'] = '5';
arr['1'] = '4';
localStorage.setItem('arr', JSON.stringify(arr));
val = JSON.parse(localStorage.getItem('arr'));
console.log(val);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.