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

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


当前回答

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

其他回答

你可以循环遍历对象:

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

下面是一个使用reduce的超级干净的Typescript解决方案:

const removeUndefinedFields = <T>(obj: T): T =>
  Object.keys(obj).reduce(
    (acc, key) =>
      obj[key as keyof T] === undefined
        ? { ...acc }
        : { ...acc, [key]: obj[key as keyof T] },
    {} as T
  )

如果你只是想从一个对象中删除未定义的顶级属性,我发现这是最简单的:

const someObject = { 空, 乙:“someString”, c: 3, d:未定义的 }; for (let [key, value] of Object.entries(someObject)) { if (value === null || value === undefined) delete someObject[key]; } console.log(“消毒”,someObject);

这可以使用递归来解决。JavaScript对象可以是一个数组,也可以有一个包含空值的数组作为值。

function removeNullValues(obj) {
  // Check weather obj is an array
  if (Array.isArray(obj)) {
    // Creating copy of obj so that index is maintained after splice
    obj.slice(0).forEach((val) => {
      if (val === null) {
        obj.splice(obj.indexOf(val), 1);
      } else if (typeof val === 'object') {
        // Check if array has an object
        removeNullValues(val);
      }
    });
  } else if (typeof obj === 'object') {
    // Check for object
    Object.keys(obj).forEach((key) => {
      if (obj[key] === null) {
        delete obj[key];
      } else if (typeof obj[key] === 'object') {
        removeNullValues(obj[key]);
      }
    });
  }
  return obj;
}

清洁物体到位

// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
   Object.keys(obj).forEach( (key) =>
      if (valsToRemoveArr.includes(obj[key])){
         delete obj[key]
      }
   })
}

cleanObj([undefined, null], obj)

纯函数

const getObjWithoutVals = (dontReturnValsArr, obj) => {
    const cleanObj = {}
    Object.entries(obj).forEach( ([key, val]) => {
        if(!dontReturnValsArr.includes(val)){
            cleanObj[key]= val
        } 
    })
    return cleanObj
}

//To get a new object without `null` or `undefined` run: 
const nonEmptyObj = getObjWithoutVals([undefined, null], obj)