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

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


当前回答

如果你使用eslint并且想要避免绊倒no-param-reassign规则,你可以使用Object。对于一个相当优雅的ES6解决方案,assign与.reduce和计算属性名结合使用:

const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };
const cleanParams = Object.keys(queryParams) 
  .filter(key => queryParams[key] != null)
  .reduce((acc, key) => Object.assign(acc, { [key]: queryParams[key] }), {});
// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }

其他回答

你可以循环遍历对象:

Var检验= { test1:空, test2:“somestring”, test3: 3, } 函数clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { 删除obj [propName]; } } 返回obj } console.log(测试); console.log(清洁(测试));

如果你担心这个属性删除不会运行到对象的proptype链,你还可以:

function clean(obj) {
  var propNames = Object.getOwnPropertyNames(obj);
  for (var i = 0; i < propNames.length; i++) {
    var propName = propNames[i];
    if (obj[propName] === null || obj[propName] === undefined) {
      delete obj[propName];
    }
  }
}

关于null和undefined的一些注意事项:

test.test1 === null; // true
test.test1 == null; // true

test.notaprop === null; // false
test.notaprop == null; // true

test.notaprop === undefined; // true
test.notaprop == undefined; // true

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' }

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

const stripUndef = obj => 
  Object.keys(obj)
   .reduce((p, c) => ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});
ES6 arrow function and ternary operator:
Object.entries(obj).reduce((acc, entry) => {
   const [key, value] = entry
  if (value !== undefined) acc[key] = value;
  return acc;
}, {})
    const obj = {test:undefined, test1:1 ,test12:0, test123:false};
    const newObj = Object.entries(obj).reduce((acc, entry) => {
       const [key, value] = entry
      if (value !== undefined) acc[key] = value;
      return acc;
    }, {})
    console.log(newObj)

函数式和不可变的方法,不需要.filter,也不需要创建超出需要的对象

Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})