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

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


当前回答

更短的ES6纯解决方案,将其转换为数组,使用过滤器函数并将其转换回对象。 也很容易创建一个函数。

顺便说一句。使用这个.length > 0我检查是否有一个空字符串/数组,因此它将删除空键。

const MY_OBJECT = { f: 'te', a: [] }

Object.keys(MY_OBJECT)
 .filter(f => !!MY_OBJECT[f] && MY_OBJECT[f].length > 0)
 .reduce((r, i) => { r[i] = MY_OBJECT[i]; return r; }, {});

JS BIN https://jsbin.com/kugoyinora/edit?js,console

其他回答

清洁物体到位

// 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)

你可以循环遍历对象:

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

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

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

除了删除属性,还可以使用非空键创建一个新对象。

const removeEmpty = (obj) => {
  return Object.keys(obj).filter(key => obj[key]).reduce(
    (newObj, key) => {
      newObj[key] = obj[key]
      return newObj
    }, {}
  )
}

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