I have a JSON object employees which I would like to populate with the data in my localstorage. I first saved my JSON object to local storage using stringify() .
sessionStorage.setItem('Employee3', JSON.stringify({id: 3, firstName: 'Dwight', lastName: 'Schrute', title: 'Assistant Regional Manager', managerId: 2, managerName: 'Michael Scott', city: 'Scranton, PA', officePhone: '570-444-4444', cellPhone: '570-333-3333', email: '[email protected]', reportCount: 0}));
Now I want to populate my employees object:
employees: {},
populate: function() {
var i = i;
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
});
},
The function $.parseJSON(sessionStorage.getItem(key)) returns the JSON object correctly. Assigning it to the employees object fails:
Uncaught TypeError: Cannot set property 'undefined' of undefined
employeesis an object whereas you are treating it as an array. How about declaringemployeesan array?ihold?