Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 代理本地存储以进行动态对象插入_Javascript_Json_Local Storage_Javascript Proxy - Fatal编程技术网

Javascript 代理本地存储以进行动态对象插入

Javascript 代理本地存储以进行动态对象插入,javascript,json,local-storage,javascript-proxy,Javascript,Json,Local Storage,Javascript Proxy,我想代理localStorage setter和getter来解析对象,并在分配时将它们保存到存储器中,就像使用常规对象一样 在保存单个项目时非常简单,但在尝试更新存储中的嵌套对象时非常复杂(对我来说) 我遇到的问题是如何使用目标参数获得对象中的正确位置。 为了克服这个问题,我将代理对象原型化回localStorage,并在每次代理调用set时解析它 它像预期的那样工作,但看起来不是正确的方法 任何建议都将不胜感激 Storage.prototype.proxy = {} Storage.pro

我想代理localStorage setter和getter来解析对象,并在分配时将它们保存到存储器中,就像使用常规对象一样

在保存单个项目时非常简单,但在尝试更新存储中的嵌套对象时非常复杂(对我来说)

我遇到的问题是如何使用目标参数获得对象中的正确位置。 为了克服这个问题,我将代理对象原型化回localStorage,并在每次代理调用set时解析它

它像预期的那样工作,但看起来不是正确的方法

任何建议都将不胜感激

Storage.prototype.proxy = {}
Storage.prototype.getAll = function () {
    data = {};
    Object.keys(this).forEach(key => {
        try {
            data[key] = JSON.parse(this[key])
        } catch {
            data[key] = this[key]
        }
    });
    this.proxy = data;
    return this.proxy;
}
Storage.prototype.update = function () {
    this.clear();
    obj = this.proxy;
    Object.keys(obj).forEach(key => {
        this.setItem(key, JSON.stringify(obj[key]));
    });
}
Storage.prototype.dynamic = new Proxy(localStorage.getAll(), handler = {
    get(target, prop) {
        if (prop == 'isProxy') return true;
        if (typeof target[prop] == 'undefined') return;
        if (!target[prop].isProxy && typeof target[prop] === 'object') {
            target[prop] = new Proxy(target[prop], handler);
        }
        return Reflect.get(...arguments);
    },
    set() {
        Reflect.set(...arguments);
        localStorage.update();
        return true;
    },
    deleteProperty(target, prop) {
        if (prop in target) {
            delete target[prop];
            localStorage.update();
        }
    }
});

const storage = localStorage.dynamic;

storage.new = {}; //create new key in storage that hold an object
storage.new.one = 1; //create new object in and assign 1 to it
console.log(storage.new.one); // prints 1