JSBin link so that you can run the code quickly.
The problem is in the comments, but from what the documentation states about how the reviver (that name is terrible), works, if you do not return a value or if you return undefined
then that property should be removed from the object. If you return the untransformed value, it stays the same.
Yet when I test it out, it looks like the entire object gets removed. The first example works just fine, the even numbers are converted to their negative and the odd numbers are unchanged.
But in the second example, I don't even get an object back, just undefined. So am I misreading the documentation or is something else wrong?
The result is just undefined in the second example.
var obj = {
one: 1,
innerObj: {
two: 2,
four: 4
},
two: 2,
three: 3,
four: 4
},
b = {},
json = JSON.stringify(obj);
/**
* This works as expected.
*/
b = JSON.parse(json, function (name, value) {
if (value % 2 === 0) {
return -value;
}
return value;
});
console.log(b);
/**
[object Object] {
four: -4,
innerObj: [object Object] {
four: -4,
two: -2
},
one: 1,
three: 3,
two: -2
}
*/
obj = {
one: 1,
innerObj: {
two: 2,
four: 4
},
two: 2,
three: 3,
four: 4
};
b = {};
json = JSON.stringify(obj);
/**
* This does not work as expected, instead of deleting the property on the object, the entire object returns undefined.
*/
b = JSON.parse(json, function (name, value) {
if (value % 2 === 0) {
return -value;
}
});
console.log(b);
// undefined