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

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


当前回答

删除所有带有null和undefined的属性

让obj = { “id”:1、 “firstName”:空, “姓”:空, “地址”:未定义的, “角色”:“客户”, “照片”:“fb79fd5d - 06 - c9 - 4097 - 8 fdc - 6 - cebf73fab26 / fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg”, “位置”:空, “idNumber”:空, }; let result = Object.entries(obj).reduce((a,[k,v]) => (v == null ?A: (A [k]=v, A)), {}); console.log(结果)

其他回答

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

下面是一个综合递归函数(最初基于@chickens的函数),它将:

递归删除你告诉它的默认值=[undefined, null, ", NaN] 正确处理常规对象、数组和Date对象

const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
  if (!defaults.length) return obj
  if (defaults.includes(obj)) return

  if (Array.isArray(obj))
    return obj
      .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
      .filter(v => !defaults.includes(v))

  return Object.entries(obj).length 
    ? Object.entries(obj)
        .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
        .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) 
    : obj
}

用法:

// based off the recursive cleanEmpty function by @chickens. // This one can also handle Date objects correctly // and has a defaults list for values you want stripped. const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) { if (!defaults.length) return obj if (defaults.includes(obj)) return if (Array.isArray(obj)) return obj .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v) .filter(v => !defaults.includes(v)) return Object.entries(obj).length ? Object.entries(obj) .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v])) .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) : obj } // testing console.log('testing: undefined \n', cleanEmpty(undefined)) console.log('testing: null \n',cleanEmpty(null)) console.log('testing: NaN \n',cleanEmpty(NaN)) console.log('testing: empty string \n',cleanEmpty('')) console.log('testing: empty array \n',cleanEmpty([])) console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000))) console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }})) console.log('testing: comprehensive obj \n', cleanEmpty({ a: 5, b: 0, c: undefined, d: { e: null, f: [{ a: undefined, b: new Date(), c: '' }] }, g: NaN, h: null })) console.log('testing: different defaults \n', cleanEmpty({ a: 5, b: 0, c: undefined, d: { e: null, f: [{ a: undefined, b: '', c: new Date() }] }, g: [0, 1, 2, 3, 4], h: '', }, [undefined, null]))

你可以剪短一点!条件

var r = {a: null, b: undefined, c:1};
for(var k in r)
   if(!r[k]) delete r[k];

使用时请记住:as @分色announcement in comments:如果值为空字符串、false或0,这也会删除属性

你可以使用空合并运算符:??因为它只检查空值和未定义值。注意,下面的例子改变了obj本身。它还删除嵌套对象的空值和未定义值。

const removeEmptyKeys = (obj) => {
    Object.entries(obj).forEach(([k, v]) => {
        (v ?? delete obj[k])
        if (v && typeof v === 'object') {
            removeEmptyKeys(v)
        }
    })
}

您可能正在寻找delete关键字。

var obj = { };
obj.theProperty = 1;
delete obj.theProperty;