0

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!

2
  • 1
    obj already is a JavaScript object, why do you want to parse() it again ? Commented Jul 19, 2014 at 10:38
  • JSON.parse() takes a string, your "obj" is not a string. Commented Jul 19, 2014 at 10:41

3 Answers 3

3

You don't have to parse the obj. It's already an object.

remove this line

obj = JSON.parse(obj);
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

0

You don't need this line: obj = JSON.parse(obj); I have updated the fiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.