首页 > 解决方案 > 如何改进清理嵌套对象的方法以删除空对象

问题描述

需要改进清理嵌套对象的方法以删除空对象

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"]}}
]}

标签: javascriptnested

解决方案


只需检查对象是否有键(这将涵盖数组和对象)。如果没有,修剪掉:

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"]}}]}

推荐阅读