Is there a clean way to remove undefined fields from an object?
i.e.
> var obj = { a: 1, b: undefined, c: 3 }
> removeUndefined(obj)
{ a: 1, c: 3 }
I came across two solutions:
_.each(query, function removeUndefined(value, key) {
if (_.isUndefined(value)) {
delete query[key];
}
});
or:
_.omit(obj, _.filter(_.keys(obj), function(key) { return _.isUndefined(obj[key]) }))
Another Javascript Solution
No additional
hasOwnProperty
check is required asObject.keys
does not look up the prototype chain and returns only the properties ofobj
.DEMO
One could also use the JQuery filter for objects
Demo here
var obj = { a: 1, b: undefined, c: 3 }
To remove
undefined
props in an object we use like thisJSON.parse(JSON.stringify(obj));
Output:
{a: 1, c: 3}
Because it doesn't seem to have been mentioned, here's my preferred method, sans side effects or external dependencies: