如何删除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]))
其他回答
更短的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
这是我对鸡肉功能的看法
这将从对象或对象数组中删除空字符串、未定义、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)), {})
}
}
删除空字段对象
for (const objectKey of Object.keys(data)) {
if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {
delete data[objectKey];
}
}
这可以使用递归来解决。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;
}
这个问题已经被彻底回答了,我只是想根据其他例子贡献我的版本:
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或”的属性。