Search code examples
javascriptangularjsjsonstringify

Why my replacer function in JSON.stringify(value, replacer) doesn't receive keys in Angular application?


Trying to implement JSON.stringify as explained here: Hide certain values in output from JSON.stringify() and exclude some fields from serialization but it doesn't work.

For example in my controller I've the following code:

.controller('ExampleController', ['$scope', function($scope) {
    $scope.event = {
      id:1,
      title: 'event title',
      users: [{
        id: 1,
        name: 'Anatoly'
      },{
        id: 2,
        name: 'Roman'
      }],
      private1: 1,
      private2: 2
    };



    var replacer = function(key, value){
        console.log(key);
    };

    $scope.stringified1 = JSON.stringify($scope.event, replacer);

    // $scope.stringified = JSON.stringify($scope.event, ['id','title','users','name']);

 }]);

Why console.log(key) prints nothing? The function itself is invoked, but key parameter is empty.

I've done plunker here: http://plnkr.co/edit/U6ZcIuPVr5RzMIBl8X6c?p=preview

I'm using Angular 1.4.9 and Chrome 48.0.2564.116

P.S. I've done this functionality with passed array and it works, but using a function can give a much more flexibility so I'd like to understand why it doesn't work.


Solution

  • Ok, it isn't clear from manual here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify but because replacer called in a recursively manner it should return object on which it's being called, root object itself too:

    Initially it gets called with an empty key representing the object being stringified

    you should return this object, if you return nothing it won't be called on other properties of this object

    and it then gets called for each property on the object or array being stringified

    So, thanks to @charlietfl hint, I fixed it, you can see fixed plunker here: http://plnkr.co/edit/a3S8yGx78b7vJSKwORw5?p=preview