Javascript - removing undefined fields from an obj

2020-01-29 04:29发布

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

10条回答
够拽才男人
2楼-- · 2020-01-29 04:54

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

查看更多
孤傲高冷的网名
3楼-- · 2020-01-29 04:58

One could also use the JQuery filter for objects

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

Demo here

查看更多
甜甜的少女心
4楼-- · 2020-01-29 04:59

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}

查看更多
We Are One
5楼-- · 2020-01-29 04:59

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}

查看更多
登录 后发表回答