globetrotter globetrotter - 7 months ago 19
Javascript Question

Remove blank attributes from an Object in Javascript

How do I remove all attributes which are

undefined
or
null
in a JavaScript object?

(Question is similar to this one for Arrays)

Answer

you can loop through the object:

var test = {
    test1 : null,
    test2 : 'somestring',
    test3 : 3,
}

for (var i in test) {
  if (test[i] === null || test[i] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete test[i];
  }
}

a few notes on null vs undefined:

test.test1 === null; // true
test.test1 == null; // true

test.test4 === null; // false
test.test4 == null; // true

test.test4 === undefined; // true
test.test4 == undefined; // true
Comments