需要改进清理嵌套对象的方法以删除空对象
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"]}}
]}发布于 2021-07-02 23:02:22
只需检查对象是否有键(将涵盖数组和对象)。如果不是,就修剪掉:
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"]}}]}发布于 2021-07-02 22:36:13
在obj上使用Remove empty objects from an object的答案之一,然后再将其放入JSON.stringify()。注意改变对象!
https://stackoverflow.com/questions/68226874
复制相似问题