Anonymoose
Anonymoose

Reputation: 2461

Add JSON objects to JSON object

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

Upvotes: 0

Views: 388

Answers (5)

bfavaretto
bfavaretto

Reputation: 71908

You have a problem with the value of this inside the forEach callback. Also, And you don't need jQuery to parse JSON.

You can do this instead:

employees: {},

populate: function() {
    var that = this;
    var i = i;
    Object.keys(sessionStorage).forEach(function(key){
        if (/^Employee/.test(key)) {
            that.employees[i] = JSON.parse(sessionStorage.getItem(key));
            i++;
        }
   });  
},

Upvotes: 1

skobaljic
skobaljic

Reputation: 9614

There is no reason to parse JSON, two simple functions will do the job (hope that was the idea):

var employees = {};

function setEmployee( data ) {
    var id = data.id;
    sessionStorage.setItem('Employee' + id, JSON.stringify( data ));
};

function getEmployee( id ) {
    employees[id] = sessionStorage.getItem('Employee' + id);
};

var oneEmployee = {
    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
};

setEmployee( oneEmployee );

getEmployee( 3 );

Upvotes: 0

Myrne Stol
Myrne Stol

Reputation: 11438

Yet another way:

Object.keys(sessionStorage).forEach((function(key){
    if (/^Employee/.test(key)) {
        this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
        i++;
    }
}).bind(this));

Calling .bind(this) on a function will return a new function bound to the value for this (in the current scope).

the advantage to this is that you don't need to remember which methods support the second "value for this" parameter. It always works. For example, this also works for when adding event listeners to DOM nodes.

tjameson's first suggestion is probably to be preferred in this specific case.

Upvotes: 2

beatgammit
beatgammit

Reputation: 20205

Array.forEach doesn't preserve this, so you'll have to preserve it yourself. Either of these will work (see mdn):

Object.keys(sessionStorage).forEach(function(key){
    if (/^Employee/.test(key)) {
        this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
        i++;
    }
}, this);

var self = this;
Object.keys(sessionStorage).forEach(function(key){
    if (/^Employee/.test(key)) {
        self.employees[i] = $.parseJSON(sessionStorage.getItem(key));
        i++;
    }
});

Also, consider using the browser's JSON.parse() instead of jQuery's. Any browser that supports Array.forEach will support JSON.parse().

Upvotes: 3

Kenneth
Kenneth

Reputation: 28737

You have a problem with the scope of this. When you are inside the foreach-callback this is not referring to the correct instance.

You need to save a reference to this before and then access the object through that reference (self in the following example):

function something(){    
    var self = this;
    ** snip **
    employees: {},

    populate: function() {
        var i = i;
        Object.keys(sessionStorage).forEach(function(key){
            if (/^Employee/.test(key)) {
                self.employees[i] = $.parseJSON(sessionStorage.getItem(key));
                i++;
            }
       });  
    },
    ** snip ** 
}

Upvotes: 1

Related Questions