Search and delete empty properties of objects

This is my array of objects:

var data = [ { "label": "HOME", "href": "web-tutor99.com", "children": [{}] }, { "href": "web-tutor99.com", "label": "HTML5" } ]; 

This is a multidimensional object, and here the children property is empty. How can I find empty properties like this and delete them using jQuery?

+4
source share
4 answers

try it

 data = [{ "label": "HOME", "href": "web-tutor99.com", "children": [{}] }, { "href": "web-tutor99.com", "label": "HTML5" }]; alert("Before : "+JSON.stringify(data)); //console.log(data); checkEmptyObj(data); alert("After : "+JSON.stringify(data)); function checkEmptyObj(data) { $.each(data, function(key, value) { if ($.isPlainObject(value) || $.isArray(value)) { checkEmptyObj(value); } //alert(key+":"+$.isEmptyObject(value)); if (value === "" || value === null || $.isEmptyObject(value)) { delete data[key]; } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
+1
source

You could do that.

 for (var i in data) { if (test[i].children === null || test[i].children === undefined || test[i].children.length<=0) { delete test[i].children; } } 

But I do not see any practical use in wasting CPU cycles on objects to remove empty objects.

Not sure what you are trying to achieve. But you better just check if it is empty and then not display if it is.

+1
source

You could just create (if nested, recursive) a function by scrolling through all the elements and check if it matters, if not, delete this property.

In your example object, a problem arises that the children property is far from empty - it is a property with the value of an array containing one empty object. Depending on your scenario, you will have to run your object multiple times, deleting empty entries step by step (maybe some optimization can be done).

As a final note, you can use for ... in to scroll through the properties of an object and for ... of to view the values ​​of the object / array.

0
source

I think the next clean piece of JS will take care of the job. You can check it out @ JSBin

 var data = [{"label":"HOME","href":"web-tutor99.com","children":[{}]},{"href":"web-tutor99.com","label":"HTML5"}]; function walkJSONObj(obj){ for (var prop in obj) { if (obj[prop].constructor === Array) { //if prop is an array walkJSONArray(obj[prop]); //go walk through the arrays obj[prop].length === 0 && delete obj[prop]; //if on return the array is empty delete it } else typeof obj[prop] === 'undefined' && delete obj[prop]; //delete undefined props } } function walkJSONArray(arr){ for (var l = arr.length-1; l >= 0; l--) { walkJSONObj(arr[l]); // go walk the item objects if (Object.keys(arr[l]).length === 0 && JSON.stringify(arr[l]) === JSON.stringify({})) { arr.splice(l, 1); // if on return the object is empty delete it } } } walkJSONArray(data); 
0
source

All Articles