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

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


当前回答

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)

其他回答

如果你想要4行纯ES7解决方案:

const clean = e => e instanceof Object ? Object.entries(e).reduce((o, [k, v]) => {
  if (typeof v === 'boolean' || v) o[k] = clean(v);
  return o;
}, e instanceof Array ? [] : {}) : e;

或者如果你喜欢更易读的版本:

function filterEmpty(obj, [key, val]) {
  if (typeof val === 'boolean' || val) {
    obj[key] = clean(val)
  };

  return obj;
}

function clean(entry) {
  if (entry instanceof Object) {
    const type = entry instanceof Array ? [] : {};
    const entries = Object.entries(entry);

    return entries.reduce(filterEmpty, type);
  }

  return entry;
}

这将保留布尔值,也将清理数组。它还通过返回一个清理过的副本来保存原始对象。

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

var testObject = { test1:“零”, test2:空, test3:“somestring”, test4: 3, test5:“定义”, test6:未定义的, } 函数removeObjectItem (obj) { For (var key in obj) { 如果(String (obj(例子))= = =“零”| |字符串(obj(例子))= = =“定义”){ 删除obj(例子); } } 返回obj } console.log (removeObjectItem (testObject))

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

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

如果你不想修改原始对象(使用一些ES6操作符):

const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);
const pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));

const objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));

过滤器(key => objectWithNulls[key])返回任何为真值的值,因此将拒绝任何值,如0或false,以及undefined或null。可以很容易地更改为过滤器(key => objectWithNulls[key] !== undefined)或类似的东西,如果这是不想要的行为。