1

How do I check for an empty JSON object in Javascript? I thought the key was

var isEmpty = (response || []).length === 0;

but this isn't it. In my JS console, I have tried

jsonresp = {}
{}
jsonresp.length
undefined

What's driving this is I have a Ruby on Rails controller that is returning the following

render json: job_id.eql?(cur_job_id) ? {} : json_obj

In the case where the controller returns the "{}" is where I'm having trouble on the JS side recognizing if it is empty or not.

Cœur
  • 37,241
  • 25
  • 195
  • 267
satish
  • 703
  • 5
  • 23
  • 52

3 Answers3

1

You can also try:

if (typeof jsonresp == 'undefined' || typeof jsonresp == 'null'){

// some logic here

}
Sanjay Vig
  • 11
  • 3
0

Shortly:

const isEmpty = !Object.keys(jsonresp).length

sultan
  • 4,543
  • 2
  • 24
  • 32
0

You can use Object.keys() function to get keys of the object as an array and then check the array to see whether it is empty.

var obj = {};
var arr = Object.keys(obj);
console.log(arr);
console.log("Is Empty : " + (arr.length == 0));
Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30