1

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.

mnvbrtn
  • 558
  • 1
  • 8
  • 27
  • What have you tried so far? You say "even recursively" so you're likely on the right track. The trick is that `typeof null === 'object'` so you just have to make sure that you evaluate for null before you recursively dive into the nested object. – Brendan Bond Jul 22 '23 at 14:13
  • Recursively remove objects with null or empty values from the JSON, including objects with child objects that have all null or empty values. Ensure the updated JSON output contains only non-null and non-empty objects, resulting in a cleaned JSON structure. – Coder Jul 22 '23 at 14:16
  • 1
    also share some code that you tried. Stackoverflow is not AI. people are here to help you on what you tried. – Coder Jul 22 '23 at 14:18

3 Answers3

2

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)
User863
  • 19,346
  • 2
  • 17
  • 41
0

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);
Harrison
  • 1,654
  • 6
  • 11
  • 19
0

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