Could you please tell me How to remove the object with all null values in json using javascript.
I need to remove the nested objects with null/empty keys too.
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"text": null,
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"definition": null
},
"GlossSee": "markup",
"window": {
"title": "Sample Konfabulator Widget",
"description": ""
}
}
}
},
"image": {
"src": null,
"name": null,
"alignment": null
},
"text": {
"data": "Click Here",
"size": null,
"style": "bold",
"name": "text1",
"hOffset": "",
"vOffset": "",
"alignment": "center",
"onMouseUp": null
}
}
}
Need the output as follows:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook."
},
"GlossSee": "markup",
"window": {
"title": "Sample Konfabulator Widget"
}
}
}
},
"text": {
"data": "Click Here",
"style": "bold",
"name": "text1",
"alignment": "center"
}
}
}
How to remove the object with null or empty keys in the whole json even recursively.
Like the image
object which has keys with empty or null values.
3
Answers
You can achieve a closer result using
replacer
/reviver
inJSON.stringify(value, replacer)
/JSON.parse(text, reviver)
Example using JSON.stringify
You can do this by recursively by checking the type on the key and then choosing to keep or remove said keys.
You may also want to kick out
undefined
values too, which could be either through more loosely checkinge.g.
data == null
will check fornull
andundefined
https://stackoverflow.com/a/359629/15291770