-1

I am writing a conditional statement which execute if an input is not empty but the issue is that input can either object or array.

if(response && response.length > 0 ) {
 // but this failed if response is an object
}

So I am looking for single condition which check for both (object and array) in one line. Moreover, I checked that typeof of array and object are object

        var object_ = {};
        var array_ = [];
        console.log('typeof object', typeof object_); // object
        console.log('typeof array', typeof array_); // object
diEcho
  • 50,018
  • 37
  • 156
  • 230

3 Answers3

4
if(Object.keys(response).length)

Simply check if there are keys in the object.

Note that Object.keys will return the following:

{} => []
{a:undefined} => ["a"]
[] => []
["a"] => [0]
"a" => [0] //strings are arraylike
undefined => Error
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
2

Use this simple solution

if(response && Object.keys(response).length > 0) {
 //works for both object and arrays
}

Check this code snippet

       var obj1 = {};
       var obj2 = {
          'test1':'test1',
          'test2':'test2'
       };
       var arr1 = [];
       var arr2 = ['a','b','c'];

       console.log(obj1 && Object.keys(obj1).length > 0);

       console.log(obj2 && Object.keys(obj2).length > 0);

       console.log(arr1 && Object.keys(arr1).length > 0);

       console.log(arr2 && Object.keys(arr2).length > 0);
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
1

Answer 2 could not tell a string from Array or Object, just run this:

let s = 'hello, world';
console.log(Object.keys(s).length); // 12 will be the output

A revision should go as:

if (response instanceof Object && Object.keys(response).length > 0)
tibetty
  • 543
  • 2
  • 9