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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With