Javascript - removing undefined fields from an object [duplicate]

左心房为你撑大大i 提交于 2019-12-17 10:32:47

问题


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

回答1:


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

jsbin

Same example using if expression:

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) => {
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
    else if (obj[key] === undefined) delete obj[key];
  });
  return obj;
};

jsbin




回答2:


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}




回答3:


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.




回答4:


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

const obj = {
  a: 1,
  b: undefined
}

const newObject = Object.keys(obj).reduce((acc, key) => {
  const _acc = acc;
  if (obj[key] !== undefined) _acc[key] = obj[key];
  return _acc;
}, {})

console.log(newObject)
// Object {a: 1}



回答5:


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.




回答6:


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



回答7:


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/




回答8:


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 :

const myObj = {
  a: 1,
  b: undefined,
  c: null, 
  d: 'hello world'
};

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

console.log(myObj);



回答9:


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




回答10:


One could also use the JQuery filter for objects

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

Demo here



来源:https://stackoverflow.com/questions/25421233/javascript-removing-undefined-fields-from-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!