简体   繁体   English

将JSON对象添加到JSON对象

[英]Add JSON objects to JSON object

I have a JSON object employees which I would like to populate with the data in my localstorage. 我有一个JSON对象员工,我想用本地存储中的数据填充。 I first saved my JSON object to local storage using stringify() . 我首先使用stringify()将JSON对象保存到本地存储中。

    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. 函数$.parseJSON(sessionStorage.getItem(key))正确返回JSON对象。 Assigning it to the employees object fails: 将其分配给雇员对象失败:

Uncaught TypeError: Cannot set property 'undefined' of undefined 未捕获的TypeError:无法设置未定义的属性“未定义”

Array.forEach doesn't preserve this , so you'll have to preserve it yourself. Array.forEach不会保留this ,因此您必须自己保留它。 Either of these will work (see mdn ): 这些都可以工作(请参阅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. 另外,考虑使用浏览器的JSON.parse()而不是jQuery的JSON.parse() Any browser that supports Array.forEach will support JSON.parse() . 任何支持Array.forEach浏览器Array.forEach将支持JSON.parse()

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). 在函数上调用.bind(this)将返回绑定this值(在当前范围内)的新函数。

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. 例如,当将事件侦听器添加到DOM节点时,这也适用。

tjameson's first suggestion is probably to be preferred in this specific case. 在这种特定情况下,tjameson的第一个建议可能是首选。

You have a problem with the value of this inside the forEach callback. 您在forEach回调中使用this的值存在问题。 Also, And you don't need jQuery to parse JSON. 此外,而且您不需要jQuery即可解析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++;
        }
   });  
},

You have a problem with the scope of this . this范围有this When you are inside the foreach-callback this is not referring to the correct instance. 当您在foreach-callback内部时,这并不表示正确的实例。

You need to save a reference to this before and then access the object through that reference (self in the following example): 您需要先保存this的引用,然后通过该引用访问对象(在以下示例中为self):

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

There is no reason to parse JSON, two simple functions will do the job (hope that was the idea): 没有理由解析JSON,两个简单的函数就可以完成工作(希望就是这样):

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM