Hide certain values in output from JSON.stringify()

后端 未结 13 1589
有刺的猬
有刺的猬 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:34

    The Mozilla docs say to return undefined (instead of "none"):

    http://jsfiddle.net/userdude/rZ5Px/

    function replacer(key,value)
    {
        if (key=="privateProperty1") return undefined;
        else if (key=="privateProperty2") return undefined;
        else return value;
    }
    
    var x = {
        x:0,
        y:0,
        divID:"xyz",
        privateProperty1: 'foo',
        privateProperty2: 'bar'
    };
    
    alert(JSON.stringify(x, replacer));
    

    Here is a duplication method, in case you decide to go that route (as per your comment).

    http://jsfiddle.net/userdude/644sJ/

    function omitKeys(obj, keys)
    {
        var dup = {};
        for (var key in obj) {
            if (keys.indexOf(key) == -1) {
                dup[key] = obj[key];
            }
        }
        return dup;
    }
    
    var x = {
        x:0,
        y:0,
        divID:"xyz",
        privateProperty1: 'foo',
        privateProperty2: 'bar'
    };
    
    alert(JSON.stringify(omitKeys(x, ['privateProperty1','privateProperty2'])));
    

    EDIT - I changed the function key in the bottom function to keep it from being confusing.

提交回复
热议问题