0

If I have data in json like this :

{"items":[{"id":"2049","channel_code":"HBD","channel_name":"HBO HD"}]}

And if you search my data to the server could not find results like this :

{"items":[]}

Of output as above, how do I read that my data does not exist or is empty?

I have written some code that I got but have not found the results I want.

This code :

var data = { Name: "John Doe", Age: 25, Address: null, CityState: "Denver, CO" };
for (member in data) {
if (data[member] != null)
    //Do something
}

or

if (myObject == '') {
   alert('this object is empty');
}

Maybe someone can help me find a way out of this example. Please help

Bertho Joris
  • 1,483
  • 5
  • 27
  • 60

3 Answers3

2

You want to check if data.items.length > 0. Assuming

var data = {"items":[]};
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • @ÁlvaroG.Vicario Not entirely sure what you mean; of course there's JSON involved, that's what's creating the array. – Anthony Grist Oct 17 '12 at 11:00
  • @AnthonyGrist There's also a text editor involved (that's creating the code that creates the JSON string) but it's also irrelevant to the problem. Many people tag as [tag:json] any sort of standard JavaScript question just because there's JSON at some point. – Álvaro González Oct 17 '12 at 11:03
  • if my code like this : for ( var i = 0; i < response.length; ++i ) { str = response[i].judul; str2 = response[i].waktu_mulai; } How i can use your code? – Bertho Joris Oct 17 '12 at 11:07
  • @BerthoJoris: I have no idea what `response` or `waktu_mulai` is. If your code is `var data = {items:[]}` you can check `if(data.items.length > 0) { /* data.items is not empty */ }` – David Hedlund Oct 17 '12 at 13:03
2

To check whether your array is empty, just use the respective length property:

if ( data['items'].length < 1 ) {
   // it's empty
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
0
for (member in data) {
if (data[member] != null)
    //Do something
}

code inside for will not run because length of data is 0

if (myObject == '') {
   alert('this object is empty');
}

myObject wont be null because the object actually is there and its an empty array

you should check for myObject.length because its an empty array

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • if my code like this for extract : for ( var i = 0; i < response.length; ++i ) { str = response[i].judul; str2 = response[i].waktu_mulai; } How i can use your code? – Bertho Joris Oct 17 '12 at 10:58