Why is the JSON.stringify() replacer function not working?

javascript, json

Solution

Stringify seems to be called, first, with an empty 'k' for the root of the object. We return undefined for that, and all processing stops.

If we change it to:

if (!k || (k == "week") )

then the result is:

{"week":45}

You won't get the nested one, since we return `undefined` for "transport" and ignore all its contents.

Problem

I have the following code: http://jsfiddle.net/8tAyu/7/ ``` var foo = { "foundation": "Mozilla", "model": "box", "week": 45, "transport": { "week": 3 }, "month": 7 }; console.log(JSON.stringify(foo, function(k, v) { if (k === "week") return v; else return undefined; })); ``` so supposedly, I thought at least the "week" that isn't nested should come back, and I will see how to make the nested one come back too. But no matter how I change it, the `console.log` prints out `undefined`, unless if I change the function simply to `return v` always, then I get back the whole object. Why is that?

Original source