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

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


当前回答

reduce helper可以做到这一点(不需要类型检查)-

const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
      if (value) {
        acc[key] = value;
      }
      return acc;
    }, {});

其他回答

你可以剪短一点!条件

var r = {a: null, b: undefined, c:1};
for(var k in r)
   if(!r[k]) delete r[k];

使用时请记住:as @分色announcement in comments:如果值为空字符串、false或0,这也会删除属性

如果有人需要使用lodash从对象中删除未定义的值,然后这里是我使用的代码。修改它以删除所有空值(null/undefined)非常简单。

function omitUndefinedDeep(obj) {
  return _.reduce(obj, function(result, value, key) {
    if (_.isObject(value)) {
      result[key] = omitUndefinedDeep(value);
    }
    else if (!_.isUndefined(value)) {
      result[key] = value;
    }
    return result;
  }, {});
}

我在我的项目中有同样的场景,并使用以下方法实现。

它适用于所有数据类型,上面提到的一些数据类型不适用于日期和空数组。

removeEmptyKeysFromObject.js

removeEmptyKeysFromObject(obj) { Object.keys(obj).forEach(key => { if (Object.prototype.toString.call(obj[key]) === '[object Date]' && (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) { delete obj[key]; } else if (obj[key] && typeof obj[key] === 'object') { this.removeEmptyKeysFromObject(obj[key]); } else if (obj[key] == null || obj[key] === '') { delete obj[key]; } if (obj[key] && typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0 && Object.prototype.toString.call(obj[key]) !== '[object Date]') { delete obj[key]; } }); return obj; }

将任何对象传递给该函数

使用Nullish合并可用ES2020

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

  return Object.fromEntries(newEntries);
};

TypeScript的泛型函数

function cleanProps(object:Record<string, string>):Record<string, string> {
  let cleanObj = {};

  Object.keys(object).forEach((key) => {
    const property = object[key];
    cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;
  });

  return cleanObj;
}

export default cleanProps;

现在假设你有一个像下面这样的对象

interface Filters{
 searchString: string;
 location: string;
 sector: string
}

const filters:Filters = {
  searchString: 'cute cats',
  location: '',
  sector: 'education',
};

您可以按照如下方式使用该函数

const result = cleanProps(filters as Record<keyof Filters, string>);
console.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }