Reputation: 77
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.
Upvotes: 0
Views: 1284
Reputation: 3720
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);
Upvotes: 0
Reputation: 996
Use this while storing:
localStorage.setItem("arr", JSON.stringify(arr));
while getting:
let val = JSON.parse(localStorage.getItem('arr'))
Upvotes: 2
Reputation: 855
localStorage
can only store strings, so you need to JSON.stringify
when setItem
and JSON.parse
when getItem
.
Upvotes: 1