Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove empty object in from an array in JS

I have an array of objects and when I stringify, it looks like this:

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

How can I remove the empty {}s?

like image 651
Rudy Avatar asked Nov 24 '15 01:11

Rudy


People also ask

How do I remove empty objects from an object?

Use a recursive function. If you have a function that receives an object and iterates it looking for empty objects, and removes them, then when it comes to an object that isn't empty, simply call the same function with that inner object as the argument.

Can you use Delete in an array in JavaScript?

JavaScript Array delete()Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

What is an empty object in JavaScript?

If the length of the array is 0 , then we know that the object is empty.


2 Answers

var newArray = array.filter(value => Object.keys(value).length !== 0); 
like image 71
djfdev Avatar answered Oct 07 '22 20:10

djfdev


You can use Array.prototype.filter to remove the empty objects before stringifying.

JSON.stringify(array.filter(function(el) {     // keep element if it's not an object, or if it's a non-empty object     return typeof el != "object" || Array.isArray(el) || Object.keys(el).length > 0; }); 
like image 23
Barmar Avatar answered Oct 07 '22 20:10

Barmar