如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
如何删除JavaScript对象中未定义或空的所有属性?
(这个问题与数组的问题类似)
当前回答
下面是一个综合递归函数(最初基于@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]))
其他回答
最简单的Lodash解决方案返回一个过滤掉空值和未定义值的对象。
_.omitBy(obj, _.isNil)
为了进行深度搜索,我使用了下面的代码,也许它对任何研究这个问题的人都有用(它不适用于循环依赖关系):
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;
}
如果有人需要欧文(和埃里克)答案的递归版本,这里是:
/**
* 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);
}
}
}
如果你只是想从一个对象中删除未定义的顶级属性,我发现这是最简单的:
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);
你也可以用…使用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(清洁对象);