Search code examples
javascriptjsonblackberry-10

Why For- in loop returns 'arg' when loop is empty


I am iterating over the JSON Object

My JSON Structure is something like this

{"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}}

 for (var tempVal in jsonObj.someinfo.Parameter) {
//print tempval

}

above loop will return correct values when 'Parameter' in JSON is filled.

If it is empty it will print arg

Empty 'Parameter' in JSON will Look Like:

{"someinfo":{"Parameter":""}}}

In order to print correct values when empty or non empty is there any way in for- in loop


Solution

  • filled Parameter is an object empty Parameter is a string

    var jsonObj1={"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}};
    var jsonObj2={"someinfo":{"Parameter":""}};
    alert("Full: "+typeof jsonObj1.someinfo.Parameter+" ---- Empty: "+typeof jsonObj2.someinfo.Parameter)

    you can't "loop in a string" so if you either change your JSON or test it like this

    if (typeof jsonObj1.someinfo.Parameter==="object") {
      for (var tempVal in jsonObj.someinfo.Parameter) {
      //print tempval
      }
     } else {
      //empty
    }