Reputation: 57
I'm trying to get an array from a JSON object, and check if it's empty, but it's giving me problems. HTML:
<p id="r"></p>
JS:
var r = document.getElementById('r');
var obj = {
"_id": "4345356",
"title": "sdfsf",
"data": []
};
obj = JSON.parse(obj);
function isEmpty(a) {
if (typeof a === 'undefined' || a.length == 0)
return true;
return false;
}
r.innerHTML = isEmpty(obj.data);
Fiddle. What did I miss? Thanks!
Upvotes: 0
Views: 2674
Reputation: 14868
As others have suggested, it appears you don't have a need what whatsoever for
obj = JSON.parse(obj);
Finally to check emptiness of an array is easy, in your case, do this:
r.innerHTML = !obj.data.length;
or
r.innerHTML = obj.data.length === 0;
But if you really have a need to define a function for this purpose, then the following should be enough:
function isEmpty(a) {
return a && !a.length;
}
Upvotes: 1
Reputation: 1000
You don't need this line: obj = JSON.parse(obj);
I have updated the fiddle.
Upvotes: 0
Reputation: 25882
You don't have to parse the obj
. It's already an object.
remove this line
obj = JSON.parse(obj);
Upvotes: 3