Hide certain values in output from JSON.stringify()

后端 未结 13 1572
有刺的猬
有刺的猬 2020-12-02 15:13

Is it possible to exclude certain fields from being included in the json string?

Here is some pseudo code

var x = {
    x:0,
    y:0,
    divID:\"xyz         


        
13条回答
  •  庸人自扰
    2020-12-02 15:31

    Another good solution: (requires underscore)

    x.toJSON = function () {
        return _.omit(this, [ "privateProperty1", "privateProperty2" ]);
    };
    

    The benefit of this solution is that anyone calling JSON.stringify on x will have correct results - you don't have to alter the JSON.stringify calls individually.

    Non-underscore version:

    x.toJSON = function () {
        var result = {};
        for (var x in this) {
            if (x !== "privateProperty1" && x !== "privateProperty2") {
                result[x] = this[x];
            }
        }
        return result;
    };
    

提交回复
热议问题