In JS why does the replacer augment (as a function) in JSON.stringify behave this way... | Sololearn: Learn to code for FREE!
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

5th Apr 2019, 12:46 PM
Dim of Wit
Dim of Wit - avatar
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
12th May 2019, 11:36 PM
David Carroll
David Carroll - avatar
+ 5
Override feature!
6th Apr 2019, 12:26 AM
Calviղ
Calviղ - avatar
+ 4
Then What's this return? JSON.stringify( obj, function(k,v){ if (k === "") return {d: 5, e:6}; else return v; } )
5th Apr 2019, 4:29 PM
Calviղ
Calviղ - avatar
+ 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}
5th Apr 2019, 1:08 PM
Dim of Wit
Dim of Wit - avatar
+ 3
Never realised there is "":obj in the object.. 😯
5th Apr 2019, 4:17 PM
Calviղ
Calviղ - avatar
+ 3
the output is {"d":5,"e":6} 🤔
5th Apr 2019, 4:59 PM
Gordon
Gordon - avatar
+ 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.
5th Apr 2019, 5:07 PM
Dim of Wit
Dim of Wit - avatar
+ 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.
13th May 2019, 6:34 AM
Dim of Wit
Dim of Wit - avatar
5th Apr 2019, 1:44 PM
Gordon
Gordon - avatar