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

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


当前回答

如果你不想原地改变,而是返回一个删除了null/undefined的克隆,你可以使用ES6的reduce函数。

// Helper to remove undefined or null properties from an object
function removeEmpty(obj) {
  // Protect against null/undefined object passed in
  return Object.keys(obj || {}).reduce((x, k) => {
    // Check for null or undefined
    if (obj[k] != null) {
      x[k] = obj[k];
    }
    return x;
  }, {});
}

其他回答

如果有人需要使用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;
  }, {});
}

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

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

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

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

清除空数组、空对象、空字符串、未定义、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。在这里学的

使用Nullish合并可用ES2020

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

  return Object.fromEntries(newEntries);
};