I'm currently studying javascript by following the series "you dont know js".
In the section "types & grammer", when discussing "JSON.stringify" function, the author mentioned
var a = { b: 42, c: "42", d: [11,22,33] }; JSON.stringify( a, ["b","c"] ); // "{"b":42,"c":"42"}" JSON.stringify( a, function(k,v){ if (k !== "c") return v; } ); // "{"b":42,"d":[11,22,33]}"Note: In the function replacer case, the key argument k is undefined for the first call (where the a object itself is being passed in). The if statement filters out the property named "c". Stringification is recursive, so the [1,2,3] array has each of its values (1, 2, and 3) passed as v to replacer, with indexes (0, 1, and 2) as k.
So I have came out with the following code, aimed at removing the value 22 from the JSON.stringify result
var a = {
b: 42,
c: "42",
d: [11, 22, 33]
};
var result = JSON.stringify(a, function(k, v) {
//since each index 0, 1, 2 of property "c" will be passed into function as "k",
//therefore if "k !== 1" should filter out value 22
if (k !== 1) {
return v;
}
});
console.log(result);
I was expecting the result to be "{"b":42,"c":"42","d":[11,33]}".
However, the result was instead "{"b":42,"c":"42","d":[11,22,33]}" (as you can see, the value 22 at index 1 of property c is not filtered out)
Did I miss understood what the author said? Am I missing something?