0

As title says, I have the following array:

var viewModel = [{}, {}, {}];

At some point in my code I may populate the 2nd element:

var viewModel = [{}, { "test" : "value" }, {}];

I need a way of evaluating if the elements are empty or not. In the above case, elements 0 and 2 will evalute to true, and element 1 will evaluate to false.

What I've Tried

I've tried comparing each element to undefined and ' ' to no avail. I know could probably check for the test property of each element (if it exists it's not empty) but I ideally wanted a way of determining this independent of any property names.

(I've tagged jQuery as I'm open to jQuery suggestions).

  • 1
    Your code probably isn't working as the array element contains an empty object, it isn't empty or undefined. You might want to look at this: http://api.jquery.com/jQuery.isEmptyObject/ or the answers here: http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object – Joe May 27 '14 at 14:47
  • @Joe - Brilliant!! Exactly what I was after. Please post as the answer and I'll mark accordingly. Thanks very much mate. –  May 27 '14 at 14:49
  • It's ok, I'd just be re-posting what someone else had put. Glad it helped you though! – Joe May 27 '14 at 14:50

4 Answers4

1
{} === {} //false

JSON.stringify({}) === JSON.stringify({}) //true

JSON.stringify(myArray[0]) === JSON.stringify({}) //true    

This might come handy in your particular case may be. I havent thought much about the loopholes also.

sabithpocker
  • 15,274
  • 1
  • 42
  • 75
0

How about this

// function to check if object is empty
function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

var viewModel = [{}, { "test" : "value" }, {}];
// loop
for(var i = 0; i < viewModel.length; i++)
{ 
    // returns true if empty, otherwise false
    console.log(isEmpty(viewModel[i]));
}
koningdavid
  • 7,903
  • 7
  • 35
  • 46
0

You can count the elements that are in each object by looping through the array.

for(var i = 0; i < test.length; i++){
  if(Object.keys(test).length == 0){
    //element array[i] is empty!
  }
}

This is only in browsers supporting Ecma-script 5.

0

Takes an array of objects and returns a new array of true/false values

function isObjectEmpty(arr) {
  return arr.map(function (el) {
    return Object.keys(el).length === 0 ? true : false;
  });
}

isObjectEmpty(yourExampleArray) // [true, false, true]

Demo

Andy
  • 61,948
  • 13
  • 68
  • 95