Javascript - 从对象中删除未定义的字段 [英] Javascript - removing undefined fields from an object

查看:121
本文介绍了Javascript - 从对象中删除未定义的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净的方法可以从对象中删除未定义的字段?

Is there a clean way to remove undefined fields from an object?

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

或:

_.omit(obj, _.filter(_.keys(obj), function(key) { return _.isUndefined(obj[key]) }))


推荐答案

使用 ES6 箭头功能和三元运算符的单线:

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

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

或使用短路评估而不是三元评估:( @Matt Langlois ,感谢您的信息!)

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

使用if表达式的相同示例:

Same example using if expression:

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

如果你想删除 null '' undefined ,请使用!obj [key] 代替 obj [key] === undefined

If you want to remove null, '' and undefined, use !obj[key] instead of obj[key] === undefined.

如果你想从嵌套对象中删除项目,可以使用递归函数:

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

这篇关于Javascript - 从对象中删除未定义的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆