0

How replacer argument function extract key and value from object value and mapped it to its key and value argument in JSON.Stringify(value, replacer, space) method.

I understood that key of the object become the key parameter of the replacer function and value become value parameter of this function.

let user={name:"anup", age:22};
JSON.stringify(user,function(key,value){
          if(typeof value==="string"){
               return undefined;
           }
           return value;
 },null);

Here name becoming the key of the replacer function and "anup" becoming the value of the replacer function thats fine, but my question is how this mapping is happening? Generally we call any method by passing argument in that method call, like

 function a(c,d){
  // logic
 }
 a(2,3);

But here in stringify method we are not passing any such thing to the replacer function or callback function, then how it is getting mapped?

Actually, I'm a newbie in javaScript world, so something I'm unable to understand. If you guide me in this regard , I'll be very thankful to you.

Anup
  • 37
  • 9

1 Answers1

3

How JSON.stringify() works internally?

Thats probably some low level, highly optimized native code. But lets assume it is just a regular JavaScript function instead, that makes things easier. The function would be defined as such:

 JSON.stringify = function(toStringify, replacer) {

Now that function has to determine what toStringify is first, e.g.:

  if(typeof toStringify === "object") {

In that case, the code has to go over all the objects key/value pairs:

  for(let key in toStringify) {
    let value = toStringify[key];

Now the code can call the replacer with those pairs:

   value = replacer(key, value);

Then a string can be built up as:

   result += `"${key}": ${JSON.stringify(value)}`;

Then that result gets returned.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thank you Jonas Wilms, your answer really helped me to understand it easily. Thank you thank you :) – Anup Dec 15 '18 at 18:27
  • If an object defines a `toJSON` method, `JSON#stringify` will actually call that method before iterating through the entries. – Koray Tugay Jul 11 '21 at 04:11