I have an array of objects and when I stringify, it looks like this:
"[[{"entrReqInv": "Neither"},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]"
How can I remove the empty {}
s?
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.
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.
If the length of the array is 0 , then we know that the object is empty.
var newArray = array.filter(value => Object.keys(value).length !== 0);
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With