Rudy
Rudy

Reputation: 749

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?

Upvotes: 53

Views: 88496

Answers (9)

Faiyaz
Faiyaz

Reputation: 41

If you want to make this a bit more readable then i recommend combining with lodash:

var filteredArray = array.filter(value => !_.isEmpty(value));

This should filter for empty object and also undefined.

Upvotes: 0

Sajid Khaki
Sajid Khaki

Reputation: 161

const arrValues = [{
  x: 100
}, {
  x: 200
}, {}];
let filteredArra = arrValues.filter(
  obj => !(obj && Object.keys(obj).length === 0)
);

Upvotes: 0

user2049674
user2049674

Reputation: 41

If your array of objects is like -

finalobj--- [ { 'patient._id': '123' },
  { 'patient.birthDate': 'lt2013-01-14', {}, {} } ]

Then use the below line to remove the blank object --

var newArray = obj.filter((value: {}) => Object.keys(value).length !== 0);

Upvotes: 4

Dude
Dude

Reputation: 339

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 only want to remove empty objects, use the above method.

Upvotes: 14

shahriar hasan
shahriar hasan

Reputation: 143

Simpler to understand:

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

Upvotes: 1

Rajesh Bose
Rajesh Bose

Reputation: 1

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);

Upvotes: -3

StackSlave
StackSlave

Reputation: 10627

Here's what I would do, for progressive enhancement reasons:

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);

Upvotes: 0

Barmar
Barmar

Reputation: 781058

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;
});

Upvotes: 13

djfdev
djfdev

Reputation: 6037

var newArray = array.filter(value => Object.keys(value).length !== 0);

Upvotes: 111

Related Questions