New course! Every coder should learn Generative AI!
Try a free lesson+ 4
In JS why does the replacer augment (as a function) in JSON.stringify behave this way...
obj = { a: 1, b: 2, c: 3 } --- Works --- JSON.stringify( obj, function(k,v){ if (k !== "c") return v; } ); // {"a": 1, "b": 2} --- Does not Work --- JSON.stringify( obj, function(k,v){ if (k === "a" || k === "b") return v; } ); // undefined
9 Answers
+ 8
Dim of Wit The reasoning provided in your followup answer was correct in that the root node was being excluded, as there is no key for the root node. Obviously, the root node is needed for subordinate nodes to be evaluated and created.
Here's an alternate option using RegEx for the 2nd/non working version in your code.
See Line #38 in the JS Tab.
if(k.match(/^[ab]?$/)) return v;
https://code.sololearn.com/W5xxj0OSCOc2/?ref=app
+ 5
Override feature!
+ 4
Then
What's this return?
JSON.stringify( obj, function(k,v){
if (k === "") return {d: 5, e:6};
else return v;
} )
+ 3
I think I've worked it out. The first call on the replacer is { "": obj } so by not including "" the whole obj ins't included. So...
--- Works ---
JSON.stringify( obj, function(k,v){
if (k === "" || k === "a" || k === "b") return v;
} );
// {"a": 1, "b": 2}
+ 3
Never realised there is "":obj in the object.. 😯
+ 3
the output is {"d":5,"e":6}
🤔
+ 3
yes I think that's right, the first call is the obj as the value with an empty ("" or undefined<del>? before toJSON is applied?</del>) then it's replaced by {d: 5, e:6} and each key/value pair is then called.
+ 3
David Carroll Thank you, makes it more eloquent with regex. It's reads clearly: start, a or b, once or zero, end. So an empty string passes as zero but not c. Now it makes sense, perfect.
+ 2