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

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


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

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

你可以循环遍历对象:

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

你可以剪短一点!条件

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,这也会删除属性


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

/**
 * 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);
        }
    }
}

JSON。Stringify删除未定义的键。

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

为了进行深度搜索,我使用了下面的代码,也许它对任何研究这个问题的人都有用(它不适用于循环依赖关系):

function removeEmptyValues(obj) {
        for (var propName in obj) {
            if (!obj[propName] || obj[propName].length === 0) {
                delete obj[propName];
            } else if (typeof obj[propName] === 'object') {
                removeEmptyValues(obj[propName]);
            }
        }
        return obj;
    }

如果你正在使用lodash或underscore.js,这里有一个简单的解决方案:

var obj = {name: 'John', age: null};

var compacted = _.pickBy(obj);

这将只适用于lodash 4,预lodash 4或下划线。js,使用_。选择(obj _.identity);


来piggypack本的回答如何解决这个问题使用lodash的_。pickBy,你也可以在姐妹库中解决这个问题:Underscore.js的_.pick。

var obj = {name: 'John', age: null};

var compacted = _.pick(obj, function(value) {
  return value !== null && value !== undefined;
});

参见:JSFiddle示例


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

ES10 - ES2019和

一个简单的一行程序(返回一个新对象)。

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

和上面一样,只是写成函数形式。

function removeEmpty(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}

此函数使用递归从嵌套对象中删除项。

function removeEmpty(obj) {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
  );
}

ES6 / ES2015和

简单的一行代码。警告:这将改变给定的对象,而不是返回一个新的对象。

Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);

单个声明(不改变给定对象)。

let o = Object.keys(obj)
  .filter((k) => obj[k] != null)
  .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});

和上面一样,只是写成函数形式。

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
}

此函数使用递归从嵌套对象中删除项。

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce(
      (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),
      {}
    );
}

与上面的函数相同,但以命令式(非函数式)风格编写。

function removeEmpty(obj) {
  const newObj = {};
  Object.entries(obj).forEach(([k, v]) => {
    if (v === Object(v)) {
      newObj[k] = removeEmpty(v);
    } else if (v != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

ES5 / ES2009例子

在过去,事情要啰嗦得多。

这是一个以函数式风格编写的非递归版本。

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = obj[k];
      return acc;
    }, {});
}

这是一个以命令式风格编写的非递归版本。

function removeEmpty(obj) {
  const newObj = {};
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      newObj[k] = removeEmpty(obj[k]);
    } else if (obj[k] != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

还有一个函数式的递归版本。

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k];
      return acc;
    }, {});
}

您可以使用JSON的组合。stringify,它的替换参数,以及JSON。解析将其转换回对象。使用此方法还意味着替换嵌套对象中的所有嵌套键。

实例对象

var exampleObject = {
  string: 'value',
  emptyString: '',
  integer: 0,
  nullValue: null,
  array: [1, 2, 3],
  object: {
    string: 'value',
    emptyString: '',
    integer: 0,
    nullValue: null,
    array: [1, 2, 3]
  },
  arrayOfObjects: [
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    },
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    }
  ]
};

替代者函数

function replaceUndefinedOrNull(key, value) {
  if (value === null || value === undefined) {
    return undefined;
  }

  return value;
}

清洁物体

exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);
exampleObject = JSON.parse(exampleObject);

CodePen例子


使用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)

Lodash:

_.omitBy({a: 1, b: null}, (v) => !v)

如果你不想原地改变,而是返回一个删除了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;
  }, {});
}

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

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

更短的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


最简单的Lodash解决方案返回一个过滤掉空值和未定义值的对象。

_.omitBy(obj, _.isNil)


如果你使用eslint并且想要避免绊倒no-param-reassign规则,你可以使用Object。对于一个相当优雅的ES6解决方案,assign与.reduce和计算属性名结合使用:

const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };
const cleanParams = Object.keys(queryParams) 
  .filter(key => queryParams[key] != null)
  .reduce((acc, key) => Object.assign(acc, { [key]: queryParams[key] }), {});
// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }

如果你想要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;
}

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


我在我的项目中有同样的场景,并使用以下方法实现。

它适用于所有数据类型,上面提到的一些数据类型不适用于日期和空数组。

removeEmptyKeysFromObject.js

removeEmptyKeysFromObject(obj) { Object.keys(obj).forEach(key => { if (Object.prototype.toString.call(obj[key]) === '[object Date]' && (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) { delete obj[key]; } else if (obj[key] && typeof obj[key] === 'object') { this.removeEmptyKeysFromObject(obj[key]); } else if (obj[key] == null || obj[key] === '') { delete obj[key]; } if (obj[key] && typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0 && Object.prototype.toString.call(obj[key]) !== '[object Date]') { delete obj[key]; } }); return obj; }

将任何对象传递给该函数


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

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

清洁物体到位

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

reduce helper可以做到这一点(不需要类型检查)-

const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
      if (value) {
        acc[key] = value;
      }
      return acc;
    }, {});

你也可以用…使用forEach扩展语法,如下所示:

设 obj = { a: 1, b: “b”, c: undefined, d: null }; let cleanObj = {}; Object.keys(obj).forEach(val => { const newVal = obj[val]; cleanObj = newVal ?{ ...cleanObj, [val]: newVal } : cleanObj; }); console.info(清洁对象);


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

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

如果你不想修改原始对象(使用一些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)或类似的东西,如果这是不想要的行为。


您可以使用json在一行中进行递归删除。Stringify的replacer参数

const removeEmptyValues = obj => (
  JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))
)

用法:

removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}

正如Emmanuel的评论中提到的,只有当数据结构只包含可以放入JSON格式的数据类型(字符串、数字、列表等)时,这种技术才有效。

(此答案已更新为使用新的Nullish Coalescing运算符。根据浏览器的支持需要,你可能想要使用这个函数代替:(k,v) => v!=零?V:未定义)


递归地删除null, undefined,空对象和空数组,返回一个副本(ES6版本)

export function skipEmpties(dirty) {
    let item;
    if (Array.isArray(dirty)) {
        item = dirty.map(x => skipEmpties(x)).filter(value => value !== undefined);
        return item.length ? item : undefined;
    } else if (dirty && typeof dirty === 'object') {
        item = {};
        Object.keys(dirty).forEach(key => {
            const value = skipEmpties(dirty[key]);
            if (value !== undefined) {
                item[key] = value;
            }
        });
        return Object.keys(item).length ? item : undefined;
    } else {
        return dirty === null ? undefined : dirty;
    }
}

函数式和不可变的方法,不需要.filter,也不需要创建超出需要的对象

Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})

我们可以使用JSON。stringify和JSON。解析以从对象中删除空白属性。

jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
               if (value == null || value == '' || value == [] || value == {})
                   return undefined;
               return value;
           });

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)), {});
  } 
}

30多个答案,但我没有看到这个简短的ES6一行程序,由于Object.assign()是一个无声地忽略任何非对象(如false)的变参数函数,因此利用了扩散操作符。

Object.assign({}, ...Object.entries(obj).map(([k,v]) => v != null && {[k]: v]))

如果你只是想从一个对象中删除未定义的顶级属性,我发现这是最简单的:

const someObject = { 空, 乙:“someString”, c: 3, d:未定义的 }; for (let [key, value] of Object.entries(someObject)) { if (value === null || value === undefined) delete someObject[key]; } console.log(“消毒”,someObject);


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)

下面是一个综合递归函数(最初基于@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]))


删除空字段对象

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

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

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或”的属性。


这是另一种选择

打字稿:

function objectDefined <T>(obj: T): T {
  const acc: Partial<T> = {};
  for (const key in obj) {
    if (obj[key] !== undefined) acc[key] = obj[key];
  }
  return acc as T;
}

Javascript:

function objectDefined(obj) {
  const acc = {};
  for (const key in obj) {
    if (obj[key] !== undefined) acc[key] = obj[key];
  }
  return acc;
}

如果你可以使用Lodash,你可以添加DeepDash递归库,并实现你想要的一些非常简洁的代码:

const prune = obj => _.filterDeep(obj, (v) => !(_.isUndefined(v) || _.isNull(v)));

调用prune(anObjectWithNulls)将返回没有未定义或空值的对象。


删除所有带有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(结果)


function filterObject(obj) {
    for (var propName in obj) {
        if (!(obj[propName] || obj[propName] === false)) {
            delete obj[propName];
        }
    }

    return obj;
}

这个函数也从对象中删除NaN值,很容易理解


使用Nullish合并可用ES2020

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

  return Object.fromEntries(newEntries);
};

这是我对鸡肉功能的看法

这将从对象或对象数组中删除空字符串、未定义、null,并且不影响Date对象

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

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

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

下面是一个使用reduce的超级干净的Typescript解决方案:

const removeUndefinedFields = <T>(obj: T): T =>
  Object.keys(obj).reduce(
    (acc, key) =>
      obj[key as keyof T] === undefined
        ? { ...acc }
        : { ...acc, [key]: obj[key as keyof T] },
    {} as T
  )

这是一个递归的ES6实现,它也可以清理属性的属性。它是一个副作用自由函数,意味着它不修改对象,因此必须使用返回对象。

function removeUndefinedProperties(obj) {
  return Object.keys(obj || {})
    .reduce((acc, key) => {
      const value = obj[key];
      switch (typeof value) {
        case 'object': {
          const cleanValue = removeUndefinedProperties(value); // recurse
          if (!Object.keys(cleanValue).length) {
            return { ...acc };
          }
          return { ...acc, [key]: cleanValue };
        }
        case 'undefined':
          return { ...acc };
        default:
          return { ...acc, [key]: value };
      }
    }, {});
}

在TypeScript中,使用unknown输入它,例如:

function removeUndefinedProperties(obj: unknown): unknown {
  return Object.keys(obj ?? {})
    .reduce((acc, key) => {
      const value = obj[key];
      switch (typeof value) {
        case 'object': {
          const cleanValue = removeUndefinedProperties(value); // recurse
          if (!Object.keys(cleanValue).length) {
            return { ...acc };
          }
          return { ...acc, [key]: cleanValue };
        }
        case 'undefined':
          return { ...acc };
        default:
          return { ...acc, [key]: value };
      }
    }, {});
}

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


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


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


TypeScript的泛型函数

function cleanProps(object:Record<string, string>):Record<string, string> {
  let cleanObj = {};

  Object.keys(object).forEach((key) => {
    const property = object[key];
    cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;
  });

  return cleanObj;
}

export default cleanProps;

现在假设你有一个像下面这样的对象

interface Filters{
 searchString: string;
 location: string;
 sector: string
}

const filters:Filters = {
  searchString: 'cute cats',
  location: '',
  sector: 'education',
};

您可以按照如下方式使用该函数

const result = cleanProps(filters as Record<keyof Filters, string>);
console.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }


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