How to Remove Empty Object From JSON in JavaScript
Hi Dev,
In this article, I will show you remove empty object in json in javascript. If you want to remove all empty object then you can use this soltution.
I will give you easy and simple example of remove null values in json using javascript. I just created one simple html file. so you can understand to remove all null values in javascript.
Example
<!DOCTYPE html>
<html>
<head>
<title>How to remove empty object from json in javascript? - NiceSnippets.com</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
const myObj = {
b:'my object',
c: '',
d: null,
f: {v: 1, x: '', y: null, m: {a:'asd'}}
};
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>
It will help you...
- How to set Date in setUTCHours() Method in JavaScript?
- How to Date sets UTC milliseconds in Javascript?
- How to Use push(), unshift(),pop() and shift() With Array in Javascript?
- How to Check if a Variable is a Number in Javascript?
- How To Format a Number Using Fixed - Point Notation in Javascript?
- How to Insert an Element into an Array in javaScript?
- How to remove duplicate elements from JavaScript Array?
- How to calculate years, months and days between two dates in javascript?