javascript - 如何改进清理嵌套对象的方法以删除空对象
问题描述
需要改进清理嵌套对象的方法以删除空对象
const sanitizeNestedObject = obj => JSON.parse(JSON.stringify(obj), (key, value) => {
if (value === null || value === "" || value === [] || value === {}) return undefined
return value
})
清洗后输出
{"expressions":[{
"hasSchemaTag":{"schemaTag":"Hardware"}},
{"hasAttribute":{"attribute":"serialNumber"}},{},{},
{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}},{},{}
]}
清洁后的预期输出
{"expressions":[{
"hasSchemaTag":{"schemaTag":"Hardware"}},
{"hasAttribute":{"attribute":"serialNumber"}},
{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}
]}
解决方案
只需检查对象是否有键(这将涵盖数组和对象)。如果没有,修剪掉:
const sanitizeNestedObject = obj => JSON.parse(JSON.stringify(obj), (key, value) => {
if (value === null || value === "" || (typeof value === 'object' && !Object.keys(value).length)) return undefined
return value
})
您当然可以将功能缩短为:
const sanitizeNestedObject = obj => JSON.parse(JSON.stringify(obj), (key, value) => {
return (value === null || value === "" || (typeof value === 'object' && !Object.keys(value).length) ? undefined : value)
})
结果:
{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}]}
为了安全起见,我也检查了其他值:
这(注意数字、字符串和空数组):
{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},{},{},[],[],["a","b","",18,0],{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}},{},{}]}
进入这个:
{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},["a","b",18,0],{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}]}
推荐阅读
- javascript - axios请求检索数据后如何使用V-For?
- java - 如何在spring中创建已经代理的类的动态代理
- c++ - 为什么 C++ 哈希函数的返回类型是 std::size_t,而不是与平台无关的类型?
- c# - 以随机方式分配任务的算法,几乎没有偏差
- r - 物料需求计划包
- python - 使用自定义变压器时如何正确腌制sklearn管道
- python - 如何在删除网格线后将图表边框角更改为圆形并更改 Excel 工作表背景的颜色
- uibutton - UIButton width doesn't increase based on text if insets are given
- laravel - Laravel 6.0 app.js 只有 require('.bootstrap');?
- spring - 在 SpringBoot 控制器中接收/发送 MultiRow 数据以及文件