Search code examples
javascriptjavascript-objects

How to remove key and value undefined in object?


how to remove key and value that are undefined from object?

for example I have

var x = {
 firstname: undefined,
 lastname: 'blabla'
}

how to get object without undefined? in the most efficient and quick way?

the result should be:

x = {
 lastname: 'blabla'
}

Solution

  • var x = {
     firstname: undefined,
     lastname: 'blabla'
    }
    
    for (let key in x) {
      if (x[key] === undefined) {
       delete x[key];
      }
    }