551

How do I remove all attributes which are undefined or null in a JavaScript object?

(Question is similar to this one for Arrays)

asked Nov 13, 2008 at 3:02
8
  • 28
    Highly suggest people ignore the top-rank and move to the ES6/ES7 versions here, stackoverflow.com/a/38340730/124486 Commented Dec 13, 2016 at 7:54
  • 5
    Also ES6 one liners without mutating object is here : stackoverflow.com/a/57625661/1602301 Commented Aug 27, 2019 at 11:40
  • 1 line answer ES6 -> JSON.parse(JSON.stringify(obj)) Commented Sep 6, 2021 at 6:27
  • 2
    Watch out! Neither of those 👆 work with arrays. Commented Dec 23, 2021 at 22:30
  • stackoverflow.com/a/71968391/8621764 Commented Apr 22, 2022 at 12:00

57 Answers 57

1
2
2

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.

answered Dec 12, 2020 at 9:17
Sign up to request clarification or add additional context in comments.

Comments

2

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
 )
answered Jan 8, 2022 at 6:26

1 Comment

Wow as keyof is new for me, thanks for sharing!
2

// 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 }
 

answered Apr 22, 2022 at 11:58

Comments

2

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));

answered Feb 20, 2023 at 21:00

1 Comment

Great snippet! I liked it better then all the rest! @Jackson Quintero
2

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))

answered Sep 23, 2023 at 15:26

Comments

1

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.

answered Jan 31, 2019 at 7:57

Comments

1

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)
answered Aug 4, 2018 at 13:47

1 Comment

This one is a nice, possibly one-liner, solution
1

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;
 });
answered Jul 25, 2019 at 6:29

2 Comments

This trick is actually valid, as long as you ensure that the Obj is JSON-serializable. And it works deep as well.
Invalid array and object comparison ({} != {} and [] != []), but otherwise approach is valid
1
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)
answered May 13, 2020 at 0:01

Comments

1

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];
 }
 }
answered Jun 16, 2020 at 10:40

Comments

1

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 ''.

answered Jul 7, 2020 at 7:55

Comments

1
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

Aziza Kasenova
1,6002 gold badges14 silver badges25 bronze badges
answered Aug 20, 2021 at 13:49

Comments

1

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);
};
answered Oct 8, 2021 at 14:54

Comments

1

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)
 }
 })
}
answered Jan 4, 2022 at 14:39

Comments

1

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 };
 }
 }, {});
}
answered Jan 19, 2022 at 13:02

Comments

1

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

answered Feb 19, 2022 at 11:05

Comments

1

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))

answered Apr 10, 2022 at 12:56

Comments

1

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' }
answered Jul 21, 2022 at 14:42

Comments

1

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;
}
answered Oct 22, 2022 at 15:39

Comments

1

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.

answered Jul 19, 2023 at 12:42

Comments

1

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" }

answered Apr 10, 2022 at 10:11

4 Comments

It'll return an array
@user1346765 You didn't read the answer very well :)
it crashes object keys
@MuhammedMoussa No, it does not crash the object keys. Run the example and check for yourself.
0

If you prefer the pure/functional approach

const stripUndef = obj => 
 Object.keys(obj)
 .reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});
answered Dec 17, 2018 at 23:19

Comments

0

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);

answered Mar 27, 2020 at 13:49

Comments

0

For simple tasks like this I like to use Ramdajs:

const foo = { a: 123, b: null, c: undefined }
pickBy(isNotNil, foo) // => { a: 123 }
answered Jun 25, 2024 at 12:24

Comments

0

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 Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations 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)

answered Aug 22, 2025 at 16:46

Comments

-1

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]))
answered Mar 2, 2020 at 9:31

1 Comment

Fails on nested structure: {1:{2:null}}
-1

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)), {})
 }
 }
answered Oct 26, 2021 at 15:57

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.