53

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

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

How can I remove the empty {}s?

1
  • @jfriend00 I edited the question to reflect proper JS object syntax. Commented Aug 18, 2018 at 13:11

9 Answers 9

111
var newArray = array.filter(value => Object.keys(value).length !== 0);
Sign up to request clarification or add additional context in comments.

5 Comments

I agree, but you should put a hint to it, and add a es5 example, because it might not work everywhere..
My answer is the ES5 version.
array.filter((item) => Object.keys(item).length);
@Sinux answer is good, but remember that calling filter() on an array does not change the original array, so you'd have to reassign it e.g. array = array.filter((item) => Object.keys(item).length);
this wont work if array contains undefined objects. i.e [{name:"abc"}, undefined ].
14

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.

Comments

13

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

5 Comments

This will also filter out empty arrays.
@Roamer-1888 Is there a way to distinguish arrays from other objects? Anyway, he says he has an array of objects, to it might not matter.
Indeed, we don't know if it matters or not. If it does, then add Array.isArray(el) to the filter.
Not really backward compatible, but still a solution.
Thank you guys!! it finally worked for me!!! and I should really upload a pic.... its a She :) thxs for the help
4

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

Comments

1

Simpler to understand:

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

1 Comment

This will work if you do: Object.keys(dictionary).length.
0

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

5 Comments

Your arguments to splice() are wrong, it should be (i, 1). But this will also skip the element after the one you splice out, because that element will become i.
It's also not clear that he wants to modify the array itself, just not include the empty elements when stringifying.
That inner loop is a pretty verbose way do to n = Object.keys(o).length;
I long ago stopped worrying about IE8. If he needs a polyfill, he can look it up.
According to this, you're missing over 14% of the Market Share this year.
0
const arrValues = [{
  x: 100
}, {
  x: 200
}, {}];
let filteredArra = arrValues.filter(
  obj => !(obj && Object.keys(obj).length === 0)
);

Comments

0

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.

Comments

-3

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

2 Comments

you may also need to add an explanation about answer
Hi, welcome to Stack Overflow. When answering a question that already has a few answers, please be sure to add some additional insight into why the response you're providing is substantive and not simply echoing what's already been vetted by the original poster. This is especially important in "code-only" answers such as the one you've provided.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.