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

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


当前回答

下面是一个使用ES6从对象中删除null值的函数式方法,而不需要只使用reduce来改变对象:

const stripNulls = (obj) => {
  return Object.keys(obj).reduce((acc, current) => {
    if (obj[current] !== null) {
      return { ...acc, [current]: obj[current] }
    }
    return acc
  }, {})
}

其他回答

Oneliner:

let obj = { a: 0, b: "string", c: undefined, d: null };

Object.keys(obj).map(k => obj[k] == undefined ? delete obj[k] : obj[k] );

控制台.log(卷);

Obj将是{a: 0, b: "string"}

清除空数组、空对象、空字符串、未定义、NaN和空值。

function objCleanUp(obj:any) {
  for (var attrKey in obj) {
    var attrValue = obj[attrKey];
    if (attrValue === null || attrValue === undefined || attrValue === "" || attrValue !== attrValue) {
      delete obj[attrKey];
    } else if (Object.prototype.toString.call(attrValue) === "[object Object]") {
      objCleanUp(attrValue);
      if(Object.keys(attrValue).length===0)delete obj[attrKey];
    } else if (Array.isArray(attrValue)) {
      attrValue.forEach(function (v,index) {
        objCleanUp(v);
        if(Object.keys(v).length===0)attrValue.splice(index,1);
      });
      if(attrValue.length===0)delete obj[attrKey];
    }
  }
}

objCleanUp(myObject)

(attrValue !== attrValue)检查NaN。在这里学的

最简单的Lodash解决方案返回一个过滤掉空值和未定义值的对象。

_.omitBy(obj, _.isNil)

这可以使用递归来解决。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;
}

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

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

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

将任何对象传递给该函数