将对象转换为JSON,省略某些(私有)属性 [英] Convert object to JSON omitting certain (private) properties

查看:150
本文介绍了将对象转换为JSON,省略某些(私有)属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用dean edwards base.js(http://dean.edwards.name/weblog/2006/03/base/)将程序组织到对象中(如果您还没有的话,base.js很棒. !!无论如何,我的问题是通用的,您不必知道base.js就能知道我的答案.

I've been using dean edwards base.js (http://dean.edwards.name/weblog/2006/03/base/) to organise my program into objects ( base.js is amazing btw, if you havent used it before !).Anyway, my question is generic and you don't have to know base.js to know my answer.

我在一个名为ref的对象中有一个属性,该属性是对DOM元素的引用,并且打算使用JSON.stringify将这个对象保存为JSON,但是可以想象,因为DOM元素是圆形的结构,我将无法将该对象转换为JSON.

I have a property in one of my objects called ref which is a reference to a DOM element, and this object is meant to be saved as JSON using JSON.stringify, but as you can imagine since DOM elements are circular structure, I won't be able to convert the object into JSON.

现在要解决此问题,我有一个名为html()的方法,该方法旨在返回ref属性,但是我需要将ref作为私有属性,只能从对象内部访问,并且因此不会发送到stringify.

Now to get around this problem I have a method called html() which is meant to return the ref property, but I need to have ref as a private property which is only accessible from within the object, and hence won't be sent to stringify.

做到这一点的最佳方法是什么?

What's the best way to do that?

推荐答案

您可能知道您无法在JavaScript中拥有私有属性.

You probably know that you cannot have private properties in JavaScript.

有趣的是,如果将对象传递给具有方法toJSONJSON.stringify,则JSON.stringify将自动调用该方法以获取该对象的JSONable表示形式.因此,您要做的就是实现此方法.

Interestingly, if you pass an object to JSON.stringify which has a method toJSON, JSON.stringify will automatically call that method to get a JSONable representation of that object. So all you have to do is implement this method.

例如,您可以创建对象的浅表副本,其中仅包含要复制的属性:

For example you can create a shallow copy of the object which only contains the properties you want to copy:

MyConstructor.prototype.toJSON = function() {
    var copy = {},
        exclude = {ref: 1};
    for (var prop in this) {
        if (!exclude[prop]) {
            copy[prop] = this[prop];
        }
    }
    return copy;
};

演示

另一种方法是使用自定义替换函数,但可能更多难以控制要排除的ref和要保留的ref(如果不同的对象具有ref属性):

Another way would be to use a custom replacer function, but it might be more difficult to control which ref to exclude and which one to keep (if different objects have ref properties):

JSON.stringify(someInstance, function(key, value) {
     if(key !== 'ref') {
         return value;
     }
});

演示

这篇关于将对象转换为JSON,省略某些(私有)属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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