javascript - 从嵌套对象(ES6)中删除空值和空值 - 清理嵌套对象
问题描述
我有一个看起来像这样的对象:
{
"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
。
我想removeNull
使用 ES6 方法来增强 this 的方法,但到目前为止我没能做到。
我还尝试了用于此如何从对象中深度删除空值、空对象和空数组的老派方法
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;
};
但它也失败了。
解决方案
您可以通过迭代对象的键/值对并首先迭代嵌套的可迭代对象然后删除不需要的键来采取直接的方法。
function clean(object) {
Object
.entries(object)
.forEach(([k, v]) => {
if (v && typeof v === 'object') {
clean(v);
}
if (v && typeof v === 'object' && !Object.keys(v).length || v === null || v === undefined) {
if (Array.isArray(object)) {
object.splice(k, 1);
} else {
delete object[k];
}
}
});
return object;
}
var object = { 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: [{ foo: null }] };
console.log(clean(object));
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- scala - 从 Scala 连接到 HDFS HA(高可用性)
- php - Laravel - 使用“with”和“where”子句进行选择的查询
- azure - Azure Web App 站点扩展未提取
- ios - SwiftEntryKit:通过点击背景关闭条目
- python - 将元素为 numpy 数组的 numpy 数组转换为 numpy 数组列表
- html - 没有重叠内容的CSS粘性页脚
- javascript - node-fetch PUT 失败 - 错误的“连接:关闭”处理?
- javascript - 是否有任何浏览器支持的“webkitSpeechRecognition”替代方案?
- postgresql - 改进删除自
- arrays - Laravel 查询生成器选择数组内的返回列