3

I use Jquery to check if my object from an ajax call is empty or not.

In this example I have made a correct AJAX call and it returns some data.

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  [{"dateTime":"2015-10-02","entries":220}]
est if object is empty: false

However in this example I have made an incorrect AJAX call that returns nothing.

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  []
test if object is empty: false

surely the test variable should be true in this case as the object is empty?

2
  • 1
    Possible duplicate of How do I test for an empty Javascript object? Commented Oct 12, 2015 at 10:54
  • 1
    isEmptyObject should only be used on plain objects, you seem to have an array, and could just do response.length instead. Commented Oct 12, 2015 at 10:54

2 Answers 2

7

Use length to check if the object is empty or not.

var isEmpty = (response || []).length === 0;
Sign up to request clarification or add additional context in comments.

10 Comments

I should probably use response.length; then. Because I just tested isPlainObject and it returned false in both cases.
@AndreasUldallLeonhard isPlainObject works on Objects, if the response is array, use arr.length to check if it is empty
response.length will throw an error if response is null or undefined. You could be more defensive and have var test = response && response.length.
@user5325596 Thanks for the case, I've updated answer
Hmm this makes no sense at all obj before Json parse: [{"dateTime":"2015-10-02","entries":220}] index.html:335 test if object is empty: 41 obj before Json parse: [] test size of object: 2 That's what happened when I did .length on both
|
-1
var jsonData = JSON.parse(responseBody);
tests['empty_or_not'] = jsonData.length === 0;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.