← Back toFront-end Tips

Transform values from a JSON representation

Written byPhuoc Nguyen
08 Apr, 2021
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:

// "{"name":"John Doe","ages":42,"phones":{}}"
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) => {
// The return value will be used in final output

// If the function returns `undefined`,
// the item will be excluded from the output
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));

// "{"name":"John Doe","ages":42,"phones":["123","456","789"]}"
Want to transform all `Set` values? No problem!
JSON.stringify(person, (key, value) => (value instanceof Set ? [...value.values()] : value));

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.