How to Remove Undefined Values from an Object in JavaScript?

Estimated read time 1 min read

To remove undefined values from an object in JavaScript, you can use a for...in loop and the delete operator. Here’s an example:

let obj = {name: "John", age: undefined, gender: "male"};
for (let key in obj) {
  if (obj[key] === undefined) {
    delete obj[key];
  }
}
console.log(obj);

This code removes all undefined values from the obj object using the for...in loop and the delete operator. The modified obj object is then logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply