tags:

views:

1602

answers:

2

How do I remove all attributes which are undefined or null in a Javascript object?

(Question is similar to this one for Arrays)

+3  A: 

You are probably looking for the delete keyword.

var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
Justice
+4  A: 

you can loop through the object:

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

for (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
Owen