Convert object to JSON omitting certain (private) properties

后端 未结 2 1501
陌清茗
陌清茗 2021-01-22 10:58

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

相关标签:
2条回答
  • 2021-01-22 11:20

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

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

    DEMO

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

    DEMO

    0 讨论(0)
  • 2021-01-22 11:23

    here is sample to to set variable visibility

    function Obj(){
           this.ref = 'public property'; // this property is public from within the object
    
           var ref = 'private proerty'; // this property is private.
    
           var self = this;
    
            this.showRef = function(){
                alert(ref);
                alert(self.ref);
            };
        }
    
    var obj = new Obj();
    obj.showRef();
    
    0 讨论(0)
提交回复
热议问题