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

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


当前回答

使用ramda#pickBy你将删除所有null, undefined和false值:

const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)

正如@manroe指出的,要保留假值,请使用isNil():

const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)

其他回答

ES6+的最短一行

过滤所有错误值("",0,false, null, undefined)

Object.entries(obj).reduce((a,[k,v]) => (v ? (a[k]=v, a) : a), {})

过滤空值和未定义值:

Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {})

仅过滤null

Object.entries(obj).reduce((a,[k,v]) => (v === null ? a : (a[k]=v, a)), {})

过滤器仅未定义

Object.entries(obj).reduce((a,[k,v]) => (v === undefined ? a : (a[k]=v, a)), {})

递归解决方案:过滤null和undefined

对象:

const cleanEmpty = obj => Object.entries(obj)
        .map(([k,v])=>[k,v && typeof v === "object" ? cleanEmpty(v) : v])
        .reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});

对于对象和数组:

const cleanEmpty = obj => {
  if (Array.isArray(obj)) { 
    return obj
        .map(v => (v && typeof v === 'object') ? cleanEmpty(v) : v)
        .filter(v => !(v == null)); 
  } else { 
    return Object.entries(obj)
        .map(([k, v]) => [k, v && typeof v === 'object' ? cleanEmpty(v) : v])
        .reduce((a, [k, v]) => (v == null ? a : (a[k]=v, a)), {});
  } 
}

如果有人需要欧文(和埃里克)答案的递归版本,这里是:

/**
 * Delete all null (or undefined) properties from an object.
 * Set 'recurse' to true if you also want to delete properties in nested objects.
 */
function delete_null_properties(test, recurse) {
    for (var i in test) {
        if (test[i] === null) {
            delete test[i];
        } else if (recurse && typeof test[i] === 'object') {
            delete_null_properties(test[i], recurse);
        }
    }
}

删除空字段对象

for (const objectKey of Object.keys(data)) {
      if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {
        delete data[objectKey];
      }
    }

JSON。Stringify删除未定义的键。

removeUndefined = function(json){
  return JSON.parse(JSON.stringify(json))
}

这个问题已经被彻底回答了,我只是想根据其他例子贡献我的版本:

function filterObject(obj, filter) {
    return Object.entries(obj)
        .map(([key, value]) => {
            return [key, value && typeof value === 'object'
                ? filterObject(value, filter)
                : value];
        })
        .reduce((acc, [key, value]) => {
            if (!filter.includes(value)) {
                acc[key] = value;
            }

            return acc;
        }, {});
}

这个解决方案的不同之处在于,你可以在第二个参数中指定你想要过滤的值,如下所示:

const filtered = filterObject(originalObject, [null, '']);

它将返回一个新对象(不改变原始对象),不包括值为null或”的属性。