如何删除JavaScript对象中未定义或空的所有属性?

(这个问题与数组的问题类似)


当前回答

使用Nullish合并可用ES2020

const filterNullishPropertiesFromObject = (obj) => {
  const newEntries = Object.entries(obj).filter(([_, value]) => {
    const nullish = value ?? null;
    return nullish !== null;
  });

  return Object.fromEntries(newEntries);
};

其他回答

如果您更喜欢纯/函数方法

const stripUndef = obj => 
  Object.keys(obj)
   .reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});

您可能正在寻找delete关键字。

var obj = { };
obj.theProperty = 1;
delete obj.theProperty;

JSON。Stringify删除未定义的键。

removeUndefined = function(json){
  return JSON.parse(JSON.stringify(json))
}

删除空字段对象

for (const objectKey of Object.keys(data)) {
      if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {
        delete data[objectKey];
      }
    }

来piggypack本的回答如何解决这个问题使用lodash的_。pickBy,你也可以在姐妹库中解决这个问题:Underscore.js的_.pick。

var obj = {name: 'John', age: null};

var compacted = _.pick(obj, function(value) {
  return value !== null && value !== undefined;
});

参见:JSFiddle示例