2
function Player(name)
    {            
        this._name = name;                     
        this._id = "Player"+(Player_ID++);
    };

var newPlayer = new Player(newUnitName);
alert(JSON.stringify(newPlayer));

What I want to do is stop displaying the id value. Is there a way to make the id variable tranient. Please help

  • 2
    Possible duplicate of [json stringify : How to exclude certain fields from the json string](http://stackoverflow.com/questions/4910567/json-stringify-how-to-exclude-certain-fields-from-the-json-string) – James Thorpe Apr 28 '16 at 07:34

2 Answers2

4

Every object has a method toJSON(), which is invoked when the object should be serialize using JSON.stringify().

From MDN article on JSON.stringify():

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized


The following example creates a different serialization function, which will exclude the _id:

var Player_ID = 0;
function Player(name) {            
 this._name = name;                     
 this._id = "Player"+(Player_ID++);
 this.toJSON = function() {
   return {
     _name: this._name
   };
 };
};

var newPlayer = new Player('Name 1');
console.log(JSON.stringify(newPlayer)); // prints {"_name": 'Name 1'}

Check the working demo.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
1

If you don't need to enumerate over this property you can use non-enumerable properties:

    function Player(name)
        {            
            this._name = name;                     
            Object.defineProperty(this, '_id', {
              enumerable: false
            });
        };

    var newUnitName = "Foo";
    var newPlayer = new Player(newUnitName);
    alert(JSON.stringify(newPlayer));
birnbaum
  • 4,718
  • 28
  • 37