57 Answers 57
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.
Comments
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
)
1 Comment
as keyof is new for me, thanks for sharing!// basic object you have to clean
// 👉️ input _object
const _object = {
a: null,
b: undefined,
email: '[email protected]',
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 protected]",mob: 88888888888 }
Comments
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));
1 Comment
you can try this:
const data = {a: null, b: 'Hello', c: 3, d: undefined, e: null};
const cleaner = obj =>
Object.fromEntries(
Object.entries(obj).filter(([, value]) => value !== null && value !== undefined),
);
console.log(cleaner(data))
Comments
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.
Comments
Clean object in place
// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
Object.keys(obj).forEach( (key) =>
if (valsToRemoveArr.includes(obj[key])){
delete obj[key]
}
})
}
cleanObj([undefined, null], obj)
Pure function
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)
1 Comment
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)
Comments
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];
}
}
Comments
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 ''.
Comments
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
Comments
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);
};
Comments
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)
}
})
}
Comments
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 };
}
}, {});
}
Comments
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
Comments
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))
Comments
A generic function with TypeScript
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' }
Comments
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;
}
Comments
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.
Comments
In-place oneliner (Vanilla JS):
let obj = { a: 0, b: "string", c: undefined, d: null };
Object.keys(obj).map(k => obj[k] == undefined ? delete obj[k] : false );
console.log(obj); // { a: 0, b: "string" }
obj will be { a: 0, b: "string" }
4 Comments
If you prefer the pure/functional approach
const stripUndef = obj =>
Object.keys(obj)
.reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});
Comments
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);
Comments
For simple tasks like this I like to use Ramdajs:
const foo = { a: 123, b: null, c: undefined }
pickBy(isNotNil, foo) // => { a: 123 }
Comments
If you expect your object to often have null or undefined values (or any other value) you can prevent them from being assigned in the first place by using a Proxy. This way you don't need to loop again through the object.
The
Proxyobject allows you to create an object that can be used in place of the original object, but which may redefine fundamentalObjectoperations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
Check the value (or key) in the set method, and only assign it if its to your liking.
const targetObejct = {}
const handler = {
set(obj, prop, value) {
if (value == "null" || value == null || value == undefined) {
return
}
return Reflect.set(...arguments)
},
}
const proxyObject = new Proxy(targetObejct, handler)
proxyObject.val1 = "null"
proxyObject.val2 = null
proxyObject.val3 = undefined
proxyObject.val4 = "some value"
console.log(proxyObject)
Comments
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]))
1 Comment
{1:{2:null}}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)), {})
}
}
JSON.parse(JSON.stringify(obj))