I have a Javascript object like:
var my_object = { a:undefined, b:2, c:4, d:undefined };
How to remove all the undefined properties? False
Since some of you might have arrived at the question looking to specifically removing only undefined
, you can use:
a combination of Lodash methods
_.omitBy(object, _.isUndefined)
the rundef package, which removes only undefined
properties
rundef(object)
If you need to recursively remove undefined
properties, the rundef package also has a recursive
option.
rundef(object, false, true);
See the documentation for more details.
I would use underscore and take care of empty strings too:
var my_object = { a:undefined, b:2, c:4, d:undefined, k: null, p: false, s: '', z: 0 };
var result =_.omit(my_object, function(value) {
return _.isUndefined(value) || _.isNull(value) || value === '';
});
console.log(result); //Object {b: 2, c: 4, p: false, z: 0}
jsbin.
If you don't want to remove false
values. Here is an example:
obj = {
"a": null,
"c": undefined,
"d": "a",
"e": false,
"f": true
}
_.pickBy(obj, x => x === false || x)
> {
"d": "a",
"e": false,
"f": true
}
if you are using lodash, you can use _.compact(array)
to remove all falsely values from an array.
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
https://lodash.com/docs/4.17.4#compact
pickBy uses identity by default:
_.pickBy({ a: null, b: 1, c: undefined, d: false });