Ask any question about JavaScript here... and get an instant response.
How can I convert a nested JavaScript object into a JSON string while skipping undefined values?
Asked on Oct 17, 2025
Answer
To convert a nested JavaScript object into a JSON string while skipping undefined values, you can use the `JSON.stringify` method with a custom replacer function. The replacer function allows you to filter out undefined values during the conversion process.
<!-- BEGIN COPY / PASTE -->
const obj = {
name: "Alice",
age: undefined,
details: {
hobbies: ["reading", "gaming"],
address: undefined
}
};
const jsonString = JSON.stringify(obj, (key, value) => {
return value === undefined ? undefined : value;
});
console.log(jsonString); // Output: {"name":"Alice","details":{"hobbies":["reading","gaming"]}}
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The `JSON.stringify` method accepts a replacer function as its second argument.
- The replacer function checks if a value is undefined and skips it by returning undefined.
- This approach ensures that undefined values are not included in the resulting JSON string.
Recommended Links:
