[javascript] Javascript - removing undefined fields from an object

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 question is related to javascript object field undefined

The answer is


A one-liner using ES6 arrow function and ternary operator:

Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});

Or use short-circuit evaluation instead of ternary: (@Matt Langlois, thanks for the info!)

Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])

Same example using if statement:

Object.keys(obj).forEach(key => {
  if (obj[key] === undefined) {
    delete obj[key];
  }
});

If you want to remove the items from nested objects as well, you can use a recursive function:

const removeEmpty = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
    else if (obj[key] !== undefined) newObj[key] = obj[key];
  });
  return newObj;
};

Mhh.. I think @Damian asks for remove undefined field (property) from an JS object. Then, I would simply do :

for (const i in myObj)  
   if (typeof myObj[i] === 'undefined')   
     delete myObj[i]; 

Short and efficient solution, in (vanilla) JS ! Example :

_x000D_
_x000D_
const myObj = {_x000D_
  a: 1,_x000D_
  b: undefined,_x000D_
  c: null, _x000D_
  d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj)  _x000D_
  if (typeof myObj[i] === 'undefined')   _x000D_
    delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
_x000D_
_x000D_


One could also use the JQuery filter for objects

var newobj = $(obj).filter(function(key) {
    return $(this)[key]!== undefined;
  })[0];

Demo here


I prefer to use something like Lodash:

import { pickBy, identity } from 'lodash'

const cleanedObject = pickBy(originalObject, identity)

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:

const cleanedObject = pickBy(originalObject, v => v !== undefined)

It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.


This solution also avoids hasOwnProperty() as Object.keys returns an array of a given object's own enumerable properties.

Object.keys(obj).forEach(function (key) {
 if(typeof obj[key] === 'undefined'){
    delete obj[key];
  }
});

and you can add this as null or '' for stricter cleaning.


var obj = { a: 1, b: undefined, c: 3 }

To remove undefined props in an object we use like this

JSON.parse(JSON.stringify(obj));

Output: {a: 1, c: 3}


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.

myObj = $.extend({}, myObj);

Because it doesn't seem to have been mentioned, here's my preferred method, sans side effects or external dependencies:

_x000D_
_x000D_
const obj = {_x000D_
  a: 1,_x000D_
  b: undefined_x000D_
}_x000D_
_x000D_
const newObject = Object.keys(obj).reduce((acc, key) => {_x000D_
  const _acc = acc;_x000D_
  if (obj[key] !== undefined) _acc[key] = obj[key];_x000D_
  return _acc;_x000D_
}, {})_x000D_
_x000D_
console.log(newObject)_x000D_
// Object {a: 1}
_x000D_
_x000D_
_x000D_


Here's a plain javascript (no library required) solution:

function removeUndefinedProps(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
            delete obj[prop];
        }
    }
}

Working demo: http://jsfiddle.net/jfriend00/djj5g5fu/


Another Javascript Solution

for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){ 
  if(typeof obj[keys[i]] === 'undefined'){
    delete obj[keys[i]];
  }
}

No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.

DEMO


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to field

String field value length in mongoDB Javascript - removing undefined fields from an object Set field value with reflection How to add additional fields to form before submit? jquery how to empty input field Add new field to every document in a MongoDB collection How to remove leading and trailing whitespace in a MySQL field? jQuery - Detect value change on hidden input field disable all form elements inside div SSRS Field Expression to change the background color of the Cell

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data