How to Remove Empty Object From JSON in JavaScript
In this article, we will explain to you how to remove empty object from JSON in javaScript. Sometimes we need to remove null values from JSON objects in javascript. Let’s look at the example below javascript JSON removes empty values.
In this example, we take a simple JSON object and give you a simple example to remove an empty object or null object from JSON. so you can see our following example.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <!DOCTYPE html> <html> <head> <title>How to Remove Empty Object From JSON in JavaScript - XpertPhp</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> var myObj = [ { "name": "bill", "age": null }, { "name": "jhon", "age": 19 }, { "name": "steve", "age": '' }, { "name": "larry", "age": 22 } ]; const removeEmptyOrNull = (obj) => { Object.keys(obj).forEach(k => (obj[k] && typeof obj[k] === 'object') && removeEmptyOrNull(obj[k]) || (!obj[k] && obj[k] !== undefined) && delete obj[k] ); return obj; }; myObj2 = removeEmptyOrNull(myObj); console.log(myObj2); </script> </body> </html> |
Output
1 | [{"name":"bill","age":null},{"name":"jhon","age":19},{"name":"steve","age":""},{"name":"larry","age":22}] |
Remove empty value from json object using filter Function
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html> <head> <title>How to Remove Empty Object From JSON in JavaScript - XpertPhp</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> var myObj = [ { "name": "bill", "age": null }, { "name": "jhon", "age": 19 }, { "name": "steve", "age": '' }, { "name": "larry", "age": 22 } ]; myObj = myObj.filter(function(x) { return x !== null }); console.log(JSON.stringify(myObj)); </script> </body> </html> |
Output
1 | [{"name":"bill","age":null},{"name":"jhon","age":19},{"name":"steve","age":""},{"name":"larry","age":22}] |
Please follow and like us: