How to remove an empty object from an array in JS

I have an array of objects, and when I'm string, it looks like this:

"[[{"entrReqInv": "Neither"},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]" 

How can I remove empty {} s?

+18
source share
6 answers
 var newArray = array.filter(value => Object.keys(value).length !== 0); 
+36
source

You can use Array.prototype.filter to remove empty objects before string formatting.

 JSON.stringify(array.filter(function(el) { // keep element if it not an object, or if it a non-empty object return typeof el != "object" || Array.isArray(el) || Object.keys(el).length > 0; }); 
+9
source

Easier to understand:

 let primaryArray = [{key:'value'},{},{},{}] let removeObsoletesArray = [] primaryArray.forEach( element => { if(element.length > 0){ removeObsoletesArray.push(element) } }) 
+1
source

Here is what I will do for progressive improvements:

 var aryAry = [[{prop: 'value'},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]; var a = aryAry[0], r = []; for(var i=0,l=a.length; i<l; i++){ var n = 0, o = a[i]; for(var q in o){ n++; } if(n > 0){ r.push(o); } } console.log(r); 
0
source

 let arr = [{a:1},{},{c:3}]; arr = _.filter(arr,v => _.keys(v).length !== 0); console.log(arr) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

arr = _.filter (arr, v => _.keys (v) .length! == 0);

0
source

I would recommend using the following code:

 var newArray = array.filter(value => JSON.stringify(value) !== '{}'); 

I did not use Object.keys (value) .length! == 0 , because it not only removes empty objects {} , but also removes empty arrays [] . If you want to delete only empty objects, use the above method.

0
source

Source: https://habr.com/ru/post/1236662/


All Articles