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]) }))
This one is easy to remember, but might be slow. Use jQuery to copy non-null properties to an empty object. No deep copy unless you add
true
as first argument.Mhh.. I think @Damian asks for
remove undefined field (property) from an JS object
. Then, I would simply do :Short and efficient solution, in (vanilla) JS ! Example :
A one-liner using ES6 arrow function and ternary operator:
Or use short-circuit evaluation instead of ternary: (@Matt Langlois, thanks for the info!)
jsbin
Same example using if expression:
If you want to remove the items from nested objects as well, you can use a recursive function:
jsbin
This solution also avoids
hasOwnProperty()
as Object.keys returns an array of a given object's own enumerable properties.and you can add this as
null
or''
for stricter cleaning.Here's a plain javascript (no library required) solution:
Working demo: http://jsfiddle.net/jfriend00/djj5g5fu/
I prefer to use something like Lodash:
Note that the identity function is just
x => x
and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...If you only want the
undefined
values removed you can do this:It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.