Transform values from a JSON representation
When transforming a given variable to the JSON representation, we might see unexpected results if the variable contains an unserializable property.
Let's consider a simple object that represents the information of a person. It has the `phones`
property that is a set of different phone numbers.
const person = {
name: 'John Doe',
ages: 42,
phones: new Set(['123', '456', '789']),
};
The set is transformed to an empty object which is unexpected output:
We can solve the issue by passing the second parameter to the `stringify`
function. It can be a function of two parameters representing the key and value of the current iterated item.
JSON.stringify(variable, (key, value) => {
return ...;
});
Here is how the phone numbers are transformed when we see the `phones`
key:
JSON.stringify(person, (key, value) => (key === 'phones' ? [...value.values()] : value));
Want to transform all `Set`
values? No problem!
JSON.stringify(person, (key, value) => (value instanceof Set ? [...value.values()] : value));
See also