Add JSON objects to JSON object

自闭症网瘾萝莉.ら 提交于 2021-02-11 12:56:53

问题


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: 'dwight@dundermifflin.com', 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


回答1:


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().




回答2:


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.




回答3:


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 ** 
}



回答4:


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++;
        }
   });  
},



回答5:


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: 'dwight@dundermifflin.com',
    reportCount: 0
};

setEmployee( oneEmployee );

getEmployee( 3 );


来源:https://stackoverflow.com/questions/16590562/add-json-objects-to-json-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!