How do I remove all attributes which are undefined
or null
in a JavaScript object?
(Question is similar to this one for Arrays)
Advertisement
Answer
You can loop through the object:
var test = { test1: null, test2: 'somestring', test3: 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } return obj } console.log(test); console.log(clean(test));
If you’re concerned about this property removal not running up object’s proptype chain, you can also:
function clean(obj) { var propNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } }
A few notes on null vs undefined:
test.test1 === null; // true test.test1 == null; // true test.notaprop === null; // false test.notaprop == null; // true test.notaprop === undefined; // true test.notaprop == undefined; // true