在JSON.parse()之后保留属性属性(可写,可配置) [英] Preserve property attributes (writeable, configurable) after JSON.parse()

查看:170
本文介绍了在JSON.parse()之后保留属性属性(可写,可配置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我正在其他地方创建一个对象并以某种方式将它传递给我的模块。也许它是在 node.js 中的服务器上创建的,也许它是在不同的模块中创建的,无论出于什么原因我都是 JSON.stringify( )输入并传递序列化版本(特别是如果它来自服务器)。但我希望这个特殊的属性是不可变的:

Lets say that I'm creating an object in somewhere else and passing it somehow to my module. Maybe it was created on the server in node.js, maybe it was created in a different module and for whatever reason I'm JSON.stringify()ing it and passing the serialized version (especially if its coming from the server). But I want this particular property to be immutable:

var foo = {};

Object.defineProperty(foo, 'bar', {
    value: 'bar',
    writeable: false,
    enumerable: true
});

console.log(foo.bar); //bar
foo.bar = 'foo';      //fails, throws err in strict
console.log(foo.bar); //still bar

var fii = JSON.parse(JSON.stringify(foo));

console.log(fii.bar); //still bar
fii.bar = 'foo';      //succeeds      
console.log(fii.bar); //now foo

有没有办法保存这个元数据,以便 bar 属性是不可变的而不单独发送?

Is there any way of preserving this meta-data so that the bar property is immutable without sending it separately?

推荐答案

您可以对属性描述符进行字符串化,例如

You could stringify the property descriptors, as in

// set up object to be serialized--from OP question
var foo = {};
Object.defineProperty(foo, 'bar', {
    value: 'bar',
    writable: false,
    enumerable: true
});

// create an object of property descriptors
var descriptors = {};
Object.keys(foo).forEach(function(key) {
    descriptors[key] = Object.getOwnPropertyDescriptor(foo, key);
});

var json = JSON.stringify(descriptors);
// "{"bar":{"value":"bar","writable":false,"enumerable":true,"configurable":false}}"

现在,重组:

descriptors = JSON.parse(json);
foo = {};
Object.defineProperties(foo, descriptors);

当然,这不适用于包含 get的访问器类型描述符和/或设置,嵌套对象等等。

Of course, this will not work with accessor-type descriptors which contain get and/or set, nested objects, etc. etc.

另一个想法是通过转入和转出方式将可写性编码为键名:

Another idea is to encode the writability into the keyname, via transformations on the way in and way out:

// Mark unwritable properties by changing keyname to 'prop:unwritable'.
function markImmutable(obj) {
    for (var p in obj) {
        if (!Object.getOwnPropertyDescriptor(obj, p).writable) {
            obj[p + ':unwritable'] = obj[p];
            delete obj[p];
        }
    }
}
markImmutable(foo)
> Object {bar:unwritable: "bar"}

然后对其进行字符串化,并在解析后进行反向转换。

Then stringify that, and after parsing do a reverse transformation.

这篇关于在JSON.parse()之后保留属性属性(可写,可配置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆