0

Need to improve method for cleaning nested object to remove empty objects as well

const sanitizeNestedObject = obj => JSON.parse(JSON.stringify(obj), (key, value) => {
    if (value === null || value === "" || value === [] || value === {}) return undefined
    return value
})

output after cleaning

{"expressions":[{
"hasSchemaTag":{"schemaTag":"Hardware"}},
{"hasAttribute":{"attribute":"serialNumber"}},{},{},
{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}},{},{}
]}

expected output after cleaning

{"expressions":[{
"hasSchemaTag":{"schemaTag":"Hardware"}},
{"hasAttribute":{"attribute":"serialNumber"}},
{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}
]}
  • Never compare against object literals, these checks are destined to fail, as JS compares objects by reference. – raina77ow Jul 02 '21 at 14:42

2 Answers2

1

Simply check if the object has keys (that will cover arrays and objects). And if not, trim out:

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
})

You could of course shorten the function to this:

const sanitizeNestedObject = obj => JSON.parse(JSON.stringify(obj), (key, value) => {
  return (value === null || value === "" || (typeof value === 'object' && !Object.keys(value).length) ? undefined : value)
})

Result:

{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}]}

To be safe, I checked with other values too:

This (note the numbers, strings and empty arrays):

{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},{},{},[],[],["a","b","",18,0],{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}},{},{}]}

Gets into this:

{"expressions":[{"hasSchemaTag":{"schemaTag":"Hardware"}},{"hasAttribute":{"attribute":"serialNumber"}},["a","b",18,0],{"hasAnySchemaTags":{"schemaTags":["UCSFanModule","UCSMemoryArray"]}}]}
0

Use one of the answers to Remove empty objects from an object on obj before throwing it into JSON.stringify(). Be aware of mutating the object!

timotgl
  • 2,865
  • 1
  • 9
  • 19