skip to Main Content

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


  1. You can achieve a closer result using replacer/reviver in JSON.stringify(value, replacer) / JSON.parse(text, reviver)

    Example using JSON.stringify

    let data = {"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}}}
    
    let json = JSON.stringify(data, (key, value) => {
        return (value === null || value === '') ? undefined : value
    }, 4)
    
    console.log(json)
    Login or Signup to reply.
  2. 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 checking
    e.g. data == null will check for null and undefined
    https://stackoverflow.com/a/359629/15291770

    const data = {
      "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
        }
      }
    }
    
    const removeKeysWithNullValues = (data) => {
      if (data === null || typeof data !== 'object') {
        return data;
      }
    
      if (Array.isArray(data)) {
        return data.map(item => removeKeysWithNullValues(item));
      }
    
      const newData = {};
      for (const key in data) {
        const value = removeKeysWithNullValues(data[key]);
        if (value !== null) {
          newData[key] = value;
        }
      }
    
      return Object.keys(newData).length > 0 ? newData : null;
    }
    
    const result = removeKeysWithNullValues(data);
    console.log(result);
    Login or Signup to reply.
  3. let obj = {
      "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
        }
      }
    };
    
    
    function nested(data) {
      for (let x in data) {
        // console.log(data[x]);
        if (typeof data[x] == 'object') {
          nested(data[x]);
        }
        if (data[x] == null) {
          delete data[x];
        }
      }
    }
    nested(obj);
    
    //filter out empty object 
    function filterout(obj) {
      for (let j in obj) {
        if (typeof obj[j] == 'object') {
          filterout(obj[j])
        }
        if (!Object.keys(obj[j]).length) {
          delete obj[j];
        }
    
      }
    }
    filterout(obj);
    
    console.log(obj);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search