7

I am getting an array of objects from my JSON response. Sometimes I am getting an array of length 1 with an empty object. How do I check that condition?

I tried with a few things-

  myarray[0]=='empty' || myarray[0] == 'undefined'
  or myarray.indexOf(0)== -1

But didn't solved the problem

DJ22T
  • 1,628
  • 3
  • 34
  • 66
JOGO
  • 285
  • 2
  • 7
  • 16
  • 1
    What do you mean by "empty"? The most "empty" value I can think of is `undefined`, but JSON can't give you an array with an `undefined` entry, as it doesn't have that concept. – T.J. Crowder Mar 24 '16 at 17:26
  • FYI, `myarray[0]=='empty'` tests whether the first array element is the **string** `'empty'`. That doesn't seem like a useful thing to try in the first place. Similarly, `myarray.indexOf(0)` tries to find the index of the *value* `0`. It seems you nee to ramp up on some JavaScript basics about values: http://eloquentjavascript.net/01_values.html, http://eloquentjavascript.net/04_data.html . – Felix Kling Mar 24 '16 at 17:33

2 Answers2

21

You can use Object.keys() method to return all property names and check it's length:

Object.keys(myarray[0]).length === 0;
madox2
  • 49,493
  • 17
  • 99
  • 99
8

It depends on what you mean by "empty."

If you mean an object with no properties

If you mean you're getting:

 [{}]

...then madox2's answer is a good way to check. Alternatively, you might have a function to do it that you can reuse:

function isEmptyObject(obj) {
    for (const key in obj) {
        if (Object.hasOwn(obj, key)) { // Remove this if you want to check for
                                       // enumerable inherited properties
            return false;
        }
    }
    return true;
}

(Object.hasOwn was added in ES2022, but is easily polyfilled.)

If you mean [null] or similar

If you want to check specifically for undefined (note the === rather than ==) (but you won't get undefined from JSON):

if (myarray[0] === undefined)

Or specifically for null (note the === rather than ==):

if (myarray[0] === null)

Or for either of those (note the == rather than ===):

if (myarray[0] == null)

Or for any falsy value (0, "", NaN, null, undefined, or of course, false):

if (!myarray[0])
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875