How do I remove all attributes which are undefined
or null
in a JavaScript object?
(Question is similar to this one for Arrays)
How do I remove all attributes which are undefined
or null
in a JavaScript object?
(Question is similar to this one for Arrays)
A simple one-liner (returning a new object).
let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
Same as above but written as a function.
function removeEmpty(obj) {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}
This function uses recursion to remove items from nested objects.
function removeEmpty(obj) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, v]) => v != null)
.map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
);
}
A simple one-liner. Warning: This mutates the given object instead of returning a new one.
Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
A single declaration (not mutating the given object).
let o = Object.keys(obj)
.filter((k) => obj[k] != null)
.reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
Same as above but written as a function.
function removeEmpty(obj) {
return Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
}
This function uses recursion to remove items from nested objects.
function removeEmpty(obj) {
return Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce(
(acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),
{}
);
}
Same as the function above, but written in an imperative (non-functional) style.
function removeEmpty(obj) {
const newObj = {};
Object.entries(obj).forEach(([k, v]) => {
if (v === Object(v)) {
newObj[k] = removeEmpty(v);
} else if (v != null) {
newObj[k] = obj[k];
}
});
return newObj;
}
In the old days things were a lot more verbose.
This is a non recursive version written in a functional style.
function removeEmpty(obj) {
return Object.keys(obj)
.filter(function (k) {
return obj[k] != null;
})
.reduce(function (acc, k) {
acc[k] = obj[k];
return acc;
}, {});
}
This is a non recursive version written in an imperative style.
function removeEmpty(obj) {
const newObj = {};
Object.keys(obj).forEach(function (k) {
if (obj[k] && typeof obj[k] === "object") {
newObj[k] = removeEmpty(obj[k]);
} else if (obj[k] != null) {
newObj[k] = obj[k];
}
});
return newObj;
}
And a recursive version written in a functional style.
function removeEmpty(obj) {
return Object.keys(obj)
.filter(function (k) {
return obj[k] != null;
})
.reduce(function (acc, k) {
acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k];
return acc;
}, {});
}
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
Shortest one liners for ES6+
Filter all falsy values ( ""
, 0
, false
, null
, undefined
)
Object.entries(obj).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {})
Filter null
and undefined
values:
Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})
Filter ONLY null
Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : (a[k]=v, a)), {})
Filter ONLY undefined
Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : (a[k]=v, a)), {})
Recursive Solutions: Filters null
and undefined
For Objects:
const cleanEmpty = obj => Object.entries(obj)
.map(([k,v])=>[k,v && typeof v === "object" ? cleanEmpty(v) : v])
.reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
For Objects and Arrays:
const cleanEmpty = obj => {
if (Array.isArray(obj)) {
return obj
.map(v => (v && typeof v === 'object') ? cleanEmpty(v) : v)
.filter(v => !(v == null));
} else {
return Object.entries(obj)
.map(([k, v]) => [k, v && typeof v === 'object' ? cleanEmpty(v) : v])
.reduce((a, [k, v]) => (v == null ? a : (a[k]=v, a)), {});
}
}
If you are using lodash or underscore.js, here is a simple solution:
var obj = {name: 'John', age: null};
var compacted = _.pickBy(obj);
This will only work with lodash 4, pre lodash 4 or underscore.js, use _.pick(obj, _.identity)
;
If somebody needs a recursive version of Owen's (and Eric's) answer, here it is:
/**
* Delete all null (or undefined) properties from an object.
* Set 'recurse' to true if you also want to delete properties in nested objects.
*/
function delete_null_properties(test, recurse) {
for (var i in test) {
if (test[i] === null) {
delete test[i];
} else if (recurse && typeof test[i] === 'object') {
delete_null_properties(test[i], recurse);
}
}
}
JSON.stringify removes the undefined keys.
removeUndefined = function(json){
return JSON.parse(JSON.stringify(json))
}
You can use a combination of JSON.stringify
, its replacer parameter, and JSON.parse
to turn it back into an object. Using this method also means the replacement is done to all nested keys within nested objects.
Example Object
var exampleObject = {
string: 'value',
emptyString: '',
integer: 0,
nullValue: null,
array: [1, 2, 3],
object: {
string: 'value',
emptyString: '',
integer: 0,
nullValue: null,
array: [1, 2, 3]
},
arrayOfObjects: [
{
string: 'value',
emptyString: '',
integer: 0,
nullValue: null,
array: [1, 2, 3]
},
{
string: 'value',
emptyString: '',
integer: 0,
nullValue: null,
array: [1, 2, 3]
}
]
};
Replacer Function
function replaceUndefinedOrNull(key, value) {
if (value === null || value === undefined) {
return undefined;
}
return value;
}
Clean the Object
exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);
exampleObject = JSON.parse(exampleObject);
Simplest possible Lodash solution to return an object with the null
and undefined
values filtered out.
_.omitBy(obj, _.isNil)
You can do a recursive removal in one line using json.stringify's replacer argument
const removeEmptyValues = obj => (
JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))
)
Usage:
removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}
As mentioned in Emmanuel's comment, this technique only worked if your data structure contains only data types that can be put into JSON format (strings, numbers, lists, etc).
(This answer has been updated to use the new Nullish Coalescing operator. depending on browser support needs you may want to use this function instead: (k,v) => v!=null ? v : undefined
)
You are probably looking for the delete
keyword.
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
you can do shorter with !
condition
var r = {a: null, b: undefined, c:1};
for(var k in r)
if(!r[k]) delete r[k];
Remember in usage : as @semicolor announce in comments: This would also delete properties if the value is an empty string, false or zero
Remove all the properties with null and undefined
let obj = {
"id": 1,
"firstName": null,
"lastName": null,
"address": undefined,
"role": "customer",
"photo": "fb79fd5d-06c9-4097-8fdc-6cebf73fab26/fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg",
"location": null,
"idNumber": null,
};
let result = Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
console.log(result)
Using ramda#pickBy you will remove all null
, undefined
and false
values:
const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)
As @manroe pointed out, to keep false
values use isNil()
:
const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)
I have same scenario in my project and achieved using following method.
It works with all data types, few mentioned above doesn't work with date and empty arrays .
removeEmptyKeysFromObject.js
removeEmptyKeysFromObject(obj) {
Object.keys(obj).forEach(key => {
if (Object.prototype.toString.call(obj[key]) === '[object Date]' && (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) {
delete obj[key];
} else if (obj[key] && typeof obj[key] === 'object') {
this.removeEmptyKeysFromObject(obj[key]);
} else if (obj[key] == null || obj[key] === '') {
delete obj[key];
}
if (obj[key]
&& typeof obj[key] === 'object'
&& Object.keys(obj[key]).length === 0
&& Object.prototype.toString.call(obj[key]) !== '[object Date]') {
delete obj[key];
}
});
return obj;
}
pass any object to this function removeEmptyKeysFromObject()
Shorter ES6 pure solution, convert it to an array, use the filter function and convert it back to an object. Would also be easy to make a function...
Btw. with this .length > 0
i check if there is an empty string / array, so it will remove empty keys.
const MY_OBJECT = { f: 'te', a: [] }
Object.keys(MY_OBJECT)
.filter(f => !!MY_OBJECT[f] && MY_OBJECT[f].length > 0)
.reduce((r, i) => { r[i] = MY_OBJECT[i]; return r; }, {});
Functional and immutable approach, without .filter
and without creating more objects than needed
Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})
For a deep search I used the following code, maybe it will be useful for anyone looking at this question (it is not usable for cyclic dependencies ) :
function removeEmptyValues(obj) {
for (var propName in obj) {
if (!obj[propName] || obj[propName].length === 0) {
delete obj[propName];
} else if (typeof obj[propName] === 'object') {
removeEmptyValues(obj[propName]);
}
}
return obj;
}
Instead of delete the property, you can also create a new object with the keys that are not null.
const removeEmpty = (obj) => {
return Object.keys(obj).filter(key => obj[key]).reduce(
(newObj, key) => {
newObj[key] = obj[key]
return newObj
}, {}
)
}
Here is a comprehensive recursive function (originally based on the one by @chickens) that will:
defaults=[undefined, null, '', NaN]
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
if (!defaults.length) return obj
if (defaults.includes(obj)) return
if (Array.isArray(obj))
return obj
.map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
.filter(v => !defaults.includes(v))
return Object.entries(obj).length
? Object.entries(obj)
.map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
.reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {})
: obj
}
USAGE:
// based off the recursive cleanEmpty function by @chickens.
// This one can also handle Date objects correctly
// and has a defaults list for values you want stripped.
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
if (!defaults.length) return obj
if (defaults.includes(obj)) return
if (Array.isArray(obj))
return obj
.map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
.filter(v => !defaults.includes(v))
return Object.entries(obj).length
? Object.entries(obj)
.map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
.reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {})
: obj
}
// testing
console.log('testing: undefined \n', cleanEmpty(undefined))
console.log('testing: null \n',cleanEmpty(null))
console.log('testing: NaN \n',cleanEmpty(NaN))
console.log('testing: empty string \n',cleanEmpty(''))
console.log('testing: empty array \n',cleanEmpty([]))
console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000)))
console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }}))
console.log('testing: comprehensive obj \n', cleanEmpty({
a: 5,
b: 0,
c: undefined,
d: {
e: null,
f: [{
a: undefined,
b: new Date(),
c: ''
}]
},
g: NaN,
h: null
}))
console.log('testing: different defaults \n', cleanEmpty({
a: 5,
b: 0,
c: undefined,
d: {
e: null,
f: [{
a: undefined,
b: '',
c: new Date()
}]
},
g: [0, 1, 2, 3, 4],
h: '',
}, [undefined, null]))
Here's an alternative
Typescript:
function objectDefined <T>(obj: T): T {
const acc: Partial<T> = {};
for (const key in obj) {
if (obj[key] !== undefined) acc[key] = obj[key];
}
return acc as T;
}
Javascript:
function objectDefined(obj) {
const acc = {};
for (const key in obj) {
if (obj[key] !== undefined) acc[key] = obj[key];
}
return acc;
}
To piggypack on Ben's answer on how to solve this problem using lodash's _.pickBy
, you can also solve this problem in the sister library: Underscore.js's _.pick
.
var obj = {name: 'John', age: null};
var compacted = _.pick(obj, function(value) {
return value !== null && value !== undefined;
});
See: JSFiddle Example
If you want 4 lines of a pure ES7 solution:
const clean = e => e instanceof Object ? Object.entries(e).reduce((o, [k, v]) => {
if (typeof v === 'boolean' || v) o[k] = clean(v);
return o;
}, e instanceof Array ? [] : {}) : e;
Or if you prefer more readable version:
function filterEmpty(obj, [key, val]) {
if (typeof val === 'boolean' || val) {
obj[key] = clean(val)
};
return obj;
}
function clean(entry) {
if (entry instanceof Object) {
const type = entry instanceof Array ? [] : {};
const entries = Object.entries(entry);
return entries.reduce(filterEmpty, type);
}
return entry;
}
This will preserve boolean values and it will clean arrays too. It also preserves the original object by returning a cleaned copy.
a reduce helper can do the trick (without type checking) -
const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
if (value) {
acc[key] = value;
}
return acc;
}, {});
With Lodash:
_.omitBy({a: 1, b: null}, (v) => !v)
If you don't want to mutate in place, but return a clone with the null/undefined removed, you could use the ES6 reduce function.
// Helper to remove undefined or null properties from an object
function removeEmpty(obj) {
// Protect against null/undefined object passed in
return Object.keys(obj || {}).reduce((x, k) => {
// Check for null or undefined
if (obj[k] != null) {
x[k] = obj[k];
}
return x;
}, {});
}
You can also use ...
spread syntax using forEach
something like this:
let obj = { a: 1, b: "b", c: undefined, d: null };
let cleanObj = {};
Object.keys(obj).forEach(val => {
const newVal = obj[val];
cleanObj = newVal ? { ...cleanObj, [val]: newVal } : cleanObj;
});
console.info(cleanObj);
Recursively remove null, undefined, empty objects and empty arrays, returning a copy (ES6 version)
export function skipEmpties(dirty) {
let item;
if (Array.isArray(dirty)) {
item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);
return item.length ? item : undefined;
} else if (dirty && typeof dirty === 'object') {
item = {};
Object.keys(dirty).forEach(key => {
const value = skipEmpties(dirty[key]);
if (value !== undefined) {
item[key] = value;
}
});
return Object.keys(item).length ? item : undefined;
} else {
return dirty === null ? undefined : dirty;
}
}
If someone needs to remove undefined
values from an object with deep search using lodash
then here is the code that I'm using. It's quite simple to modify it to remove all empty values (null
/undefined
).
function omitUndefinedDeep(obj) {
return _.reduce(obj, function(result, value, key) {
if (_.isObject(value)) {
result[key] = omitUndefinedDeep(value);
}
else if (!_.isUndefined(value)) {
result[key] = value;
}
return result;
}, {});
}
If you use eslint and want to avoid tripping the the no-param-reassign rule, you can use Object.assign in conjunction with .reduce and a computed property name for a fairly elegant ES6 solution:
const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };
const cleanParams = Object.keys(queryParams)
.filter(key => queryParams[key] != null)
.reduce((acc, key) => Object.assign(acc, { [key]: queryParams[key] }), {});
// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }
Here is a functional way to remove nulls
from an Object using ES6 without mutating the object using only reduce
:
const stripNulls = (obj) => {
return Object.keys(obj).reduce((acc, current) => {
if (obj[current] !== null) {
return { ...acc, [current]: obj[current] }
}
return acc
}, {})
}
If you're okay with using Lodash, you can add the DeepDash recursive library and achieve what you want with some pretty concise code:
const prune = obj => _.filterDeep(obj, (v) => !(_.isUndefined(v) || _.isNull(v)));
Calling prune(anObjectWithNulls)
will return the object without undefined
or null
values.
Oneliner (Vanilla JS):
let obj = { a: 0, b: "string", c: undefined, d: null };
Object.keys(obj).map(k => obj[k] == undefined ? delete obj[k] : obj[k] );
console.log(obj);
obj
will be { a: 0, b: "string" }
// basic object you have to clean
// ️ input _object
const _object = {
a: null,
b: undefined,
email: 'email@test.com',
mob:88888888888,
add:""
};
// kays you have to remove having values included in array
const CLEANER_VALUES = [null, undefined, '']
// function to clean object pass the raw object and value format you have to clean
const objectCleaner = (_object, _CLEANER_VALUES = CLEANER_VALUES) =>{
const cleanedObj = {..._object};
Object.keys(cleanedObj).forEach(key => {
if (_CLEANER_VALUES.includes(cleanedObj[key])) {
delete cleanedObj[key];
}});
return cleanedObj;
}
// calling function
const __cleandedObject = objectCleaner(_object, CLEANER_VALUES);
console.log('yup you have cleaned object', __cleandedObject);
// ️ output { email: "email@test.com",mob: 88888888888 }
// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
Object.keys(obj).forEach( (key) =>
if (valsToRemoveArr.includes(obj[key])){
delete obj[key]
}
})
}
cleanObj([undefined, null], obj)
const getObjWithoutVals = (dontReturnValsArr, obj) => {
const cleanObj = {}
Object.entries(obj).forEach( ([key, val]) => {
if(!dontReturnValsArr.includes(val)){
cleanObj[key]= val
}
})
return cleanObj
}
//To get a new object without `null` or `undefined` run:
const nonEmptyObj = getObjWithoutVals([undefined, null], obj)
If you don't want to modify the original object (using some ES6 operators):
const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);
const pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));
const objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));
The filter(key => objectWithNulls[key])
returns anything that is truthy, so will reject any values such as0
or false
, as well as undefined
or null
. Can be easily changed to filter(key => objectWithNulls[key] !== undefined)
or something similar if this is unwanted behaviour.
We can use JSON.stringify and JSON.parse to remove blank attributes from an object.
jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
if (value == null || value == '' || value == [] || value == {})
return undefined;
return value;
});
ES6 arrow function and ternary operator:
Object.entries(obj).reduce((acc, entry) => {
const [key, value] = entry
if (value !== undefined) acc[key] = value;
return acc;
}, {})
const obj = {test:undefined, test1:1 ,test12:0, test123:false};
const newObj = Object.entries(obj).reduce((acc, entry) => {
const [key, value] = entry
if (value !== undefined) acc[key] = value;
return acc;
}, {})
console.log(newObj)
remove empty field object
for (const objectKey of Object.keys(data)) {
if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {
delete data[objectKey];
}
}
This question has been thoroughly answered already, i'd just like to contribute my version based on other examples given:
function filterObject(obj, filter) {
return Object.entries(obj)
.map(([key, value]) => {
return [key, value && typeof value === 'object'
? filterObject(value, filter)
: value];
})
.reduce((acc, [key, value]) => {
if (!filter.includes(value)) {
acc[key] = value;
}
return acc;
}, {});
}
What makes this solution different is the ability to specify which values you'd like to filter in the second parameter like this:
const filtered = filterObject(originalObject, [null, '']);
Which will return a new object (does not mutate the original object) not including the properties with a value of null
or ''
.
function filterObject(obj) {
for (var propName in obj) {
if (!(obj[propName] || obj[propName] === false)) {
delete obj[propName];
}
}
return obj;
}
This function also removes NaN value from an object and easy to understand
Using Nullish coalescing available ES2020
const filterNullishPropertiesFromObject = (obj) => {
const newEntries = Object.entries(obj).filter(([_, value]) => {
const nullish = value ?? null;
return nullish !== null;
});
return Object.fromEntries(newEntries);
};
You can do this using the nullish coalescing operator: ?? since that checks only for null and undefined values. Note that the example below changes obj itself. It also deletes null and undefined values of nested objects.
const removeEmptyKeys = (obj) => {
Object.entries(obj).forEach(([k, v]) => {
(v ?? delete obj[k])
if (v && typeof v === 'object') {
removeEmptyKeys(v)
}
})
}
Here is a super clean Typescript solution using reduce
:
const removeUndefinedFields = <T>(obj: T): T =>
Object.keys(obj).reduce(
(acc, key) =>
obj[key as keyof T] === undefined
? { ...acc }
: { ...acc, [key]: obj[key as keyof T] },
{} as T
)
Here's recursive ES6 implementation that cleans up properties of the properties as well. It's a side-effect free function meaning that it does not modify the object so the return object must be used.
function removeUndefinedProperties(obj) {
return Object.keys(obj || {})
.reduce((acc, key) => {
const value = obj[key];
switch (typeof value) {
case 'object': {
const cleanValue = removeUndefinedProperties(value); // recurse
if (!Object.keys(cleanValue).length) {
return { ...acc };
}
return { ...acc, [key]: cleanValue };
}
case 'undefined':
return { ...acc };
default:
return { ...acc, [key]: value };
}
}, {});
}
In TypeScript, type it using unknown
such as:
function removeUndefinedProperties(obj: unknown): unknown {
return Object.keys(obj ?? {})
.reduce((acc, key) => {
const value = obj[key];
switch (typeof value) {
case 'object': {
const cleanValue = removeUndefinedProperties(value); // recurse
if (!Object.keys(cleanValue).length) {
return { ...acc };
}
return { ...acc, [key]: cleanValue };
}
case 'undefined':
return { ...acc };
default:
return { ...acc, [key]: value };
}
}, {});
}
Cleans empty array, empty object, empty string, undefined, NaN and null values.
function objCleanUp(obj:any) {
for (var attrKey in obj) {
var attrValue = obj[attrKey];
if (attrValue === null || attrValue === undefined || attrValue === "" || attrValue !== attrValue) {
delete obj[attrKey];
} else if (Object.prototype.toString.call(attrValue) === "[object Object]") {
objCleanUp(attrValue);
if(Object.keys(attrValue).length===0)delete obj[attrKey];
} else if (Array.isArray(attrValue)) {
attrValue.forEach(function (v,index) {
objCleanUp(v);
if(Object.keys(v).length===0)attrValue.splice(index,1);
});
if(attrValue.length===0)delete obj[attrKey];
}
}
}
objCleanUp(myObject)
(attrValue !== attrValue) checks for NaN. Learned it here
var testObject = {
test1: "null",
test2: null,
test3: 'somestring',
test4: 3,
test5: "undefined",
test6: undefined,
}
function removeObjectItem(obj){
for (var key in obj) {
if (String(obj[key]) === "null" || String(obj[key]) === "undefined") {
delete obj[key];
}
}
return obj
}
console.log(removeObjectItem(testObject))
function cleanProps(object:Record<string, string>):Record<string, string> {
let cleanObj = {};
Object.keys(object).forEach((key) => {
const property = object[key];
cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;
});
return cleanObj;
}
export default cleanProps;
now lets say you have a object like the following
interface Filters{
searchString: string;
location: string;
sector: string
}
const filters:Filters = {
searchString: 'cute cats',
location: '',
sector: 'education',
};
You can use the function as following
const result = cleanProps(filters as Record<keyof Filters, string>);
console.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }
This could be solved using Recursion. JavaScript objects could be an array and could have array with null values as a value.
function removeNullValues(obj) {
// Check weather obj is an array
if (Array.isArray(obj)) {
// Creating copy of obj so that index is maintained after splice
obj.slice(0).forEach((val) => {
if (val === null) {
obj.splice(obj.indexOf(val), 1);
} else if (typeof val === 'object') {
// Check if array has an object
removeNullValues(val);
}
});
} else if (typeof obj === 'object') {
// Check for object
Object.keys(obj).forEach((key) => {
if (obj[key] === null) {
delete obj[key];
} else if (typeof obj[key] === 'object') {
removeNullValues(obj[key]);
}
});
}
return obj;
}
There are many valid answers, I was able to solve using a for...in inside add coalescing operator which allows me to know if it is null or undefined to eliminate it
const test = {
test1: null,
test2: "somestring",
test3: 3,
test4: undefined
};
const clean = (obj) => {
for (let propName in obj) obj[propName] ?? delete obj[propName];
return obj;
};
console.log(clean(test));
My way to go for removing undefined properties from an object
TYPESCRIPT
Object.keys(data).forEach((k) => !(data as any)[k] && delete (data as any)[k]);
JAVASCRIPT
Object.keys(data).forEach((k) => !data[k] && delete data[k]);
Cleaner and shorter version of this answer.
If you prefer the pure/functional approach
const stripUndef = obj =>
Object.keys(obj)
.reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});
If you just want to remove undefined top-level properties from an object, I find this to be the easiest:
const someObject = {
a: null,
b: 'someString',
c: 3,
d: undefined
};
for (let [key, value] of Object.entries(someObject)) {
if (value === null || value === undefined) delete someObject[key];
}
console.log('Sanitized', someObject);
30+ answers but I didn't see this short ES6 one-liner, utilizing the spread operator thanks to Object.assign()
being a vararg function that silently ignores any non-objects (like false
).
Object.assign({}, ...Object.entries(obj).map(([k,v]) => v != null && {[k]: v]))
Here's my version of chiken's function
This will remove empty strings, undefined, null from object or object arrays and don't affect Date objects
const removeEmpty = obj => {
if (Array.isArray(obj)) {
return obj.map(v => (v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v)).filter(v => v)
} else {
return Object.entries(obj)
.map(([k, v]) => [k, v && !(v instanceof Date) && typeof v === 'object' ? removeEmpty(v) : v])
.reduce((a, [k, v]) => (typeof v !== 'boolean' && !v ? a : ((a[k] = v), a)), {})
}
}