Reputation: 5915
I'm storing a bunch of values in localStorage. An array with JSON objects in it to be specific. When I want to add another object to that array here is how I pull it, parse it, push onto the array and set it again.
var clickedItem = sessionStorage.getItem('location'),
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
Later on if I pull the array and loop through the array my properties are undefined.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
}
PS. The JSON object looks completely normal when I console it. Any ideas why the props would be undefined?
UPDATE: data is in fact an array and looping through it does give me each value from within it. However each JSON object in the array is no longer an object and must be JSON.parsed to "recreate" an object out of the string that it is.
This was a really great lesson on storing JSON objects within an array in localStorage.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
var obj = JSON.parse(data[i]); // parse it instead
console.log(obj.title); // use it as an object now
}
Upvotes: 3
Views: 3277
Reputation: 3087
localStorage only supports strings. Use JSON.stringify() and JSON.parse().
//demo value
var clickedItem = {"testValue":111};
var interests = [{'a':1},{'b':2},{'c':4}];
localStorage.setItem('interests', JSON.stringify(interests));
//demo value end
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
console.log(interestsParsed);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i]);
}
I think you did't stringify value of interests,(before getting value at line no.3)
Upvotes: 0
Reputation: 4348
My assumption is that you are trying to stringify
a complex object, probably something like a DOM object or another built-in API's object. What happens is that JSON.stringify
will strip the object out of all methods, and this includes internal setters and getters, and you remain with an empty (or almost empty) object.
My solution in such cases is to parse the complex object into a simple one containing only the properties you need in the formatting of your choosing.
Upvotes: 2
Reputation: 62773
JSON.parse()
returns an object
but you're treating it as an array
. Instead of pushing to the array, add a new item to the object.
Upvotes: 0