← 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

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

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.
Phước Nguyễn