【发布时间】:2018-09-17 12:33:15
【问题描述】:
我得到了一个看起来像这样的对象:
{
"a": "string not empty",
"b": {
"c": "string not empty",
},
"d": {
"e": false,
"f": 0,
"g": true,
"h": 10
},
"i": {
"j": 0,
"k": null
},
"l": {
"m": null
},
"n": {
"o": 1,
"p": "string (not empty)",
"q": {}
},
"r": [],
"l": "2000-01-01T01:01:00.000Z",
}
感谢此处提供的代码:https://stackoverflow.com/a/38364486/3912805 我现在可以删除嵌套对象的所有 null 值。
我使用这个功能至今removeNull:
removeNull = (obj) => {
Object.keys(obj).forEach(key =>
(obj[key] && typeof obj[key] === 'object') && removeNull(obj[key]) ||
(obj[key] === undefined || obj[key] === null) && delete obj[key]
);
return obj;
};
但我想增强此功能,以允许我删除嵌套对象中可能存在的所有空数组或任何空集合。
最终结果应该是没有 k, l & m, q, r, l:
{
"a": "string not empty",
"b": {
"c": "string not empty",
},
"d": {
"e": false,
"f": 0,
"g": true,
"h": 10
},
"i": {
"j": 0
},
"n": {
"o": 1,
"p": "string (not empty)"
},
"l": "2000-01-01T01:01:00.000Z",
}
我需要保留所有设置为 0 或 false 的值。
我想用 ES6 的方法来增强这个removeNull 的方法,但是到目前为止我没能做到。
我还尝试了用于此 How to deeply remove null values, empty objects and empty array from an object 的老式方法
itemToBool = item => {
if (typeof item !== 'object' || item === null) return item;
const cleanedItem = cleanObject(item);
return Object.keys(cleanedItem).length !== 0 && cleanedItem;
};
cleanObject = obj => {
if (Array.isArray(obj)) {
const newArr = obj.map(itemToBool).filter(Boolean);
return newArr.length && newArr;
}
const newObj = Object.entries(obj).reduce((a, [key, val]) => {
const newVal = itemToBool(val);
if (newVal !== null || newVal === false) a[key] = newVal;
return a;
}, {});
return Object.keys(newObj).length > 0 && newObj;
};
但它也失败了。
【问题讨论】: