0

I am trying to detect first index name from my JSON object and this data come from API ..

if success data will return something like this :

var setRecharge = [{"data":{"transaction_id":"502014","tr_time":"2013-06-18 15:34:46","tr_channel":"WEB","opening_balance_a":"1000.00","closing_balance_a":"990.00"}}];

and if failed it will return :

var setRecharge = [{"error":{"code":"AccountA","message":"Problem with A account: Password is not correct"}}];

so from here i need to know the first index is data or error so i can continue wil if else statement ..

i try to refer this topic Javascript: Getting the first index of an object but not sure why it's not working and my data also has bracket and block.

Community
  • 1
  • 1
rusly
  • 1,504
  • 6
  • 28
  • 62
  • 2
    Why not just check for the existence of `error`? Much cleaner than evaluating the physical position of it within the object... – BenM Jun 18 '13 at 09:19
  • You need to Parse JSON, then you can access the object as a standard array http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – Novocaine Jun 18 '13 at 09:20
  • you should never rely on object properties key positioning as they are not guaranted at all in the ecma specification – malko Jun 18 '13 at 09:23

3 Answers3

1

Rather than checking the name of the element, you can check whether error is present:

if(setRecharge[0].hasOwnProperty("error")) {
    //you have an error - deal with it
}
else if(setRecharge[0].hasOwnProperty("data")) {
    //you have your data - deal with it
}
else {
    //something went wrong - you got neither
}
Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

I'd recommend just checking if the object has the error property, and then handling it. It's a much cleaner solution than checking the name of the first property. What if the order of the properties changes?

The following should work for your needs:

if(setRechargeRate[0].hasOwnProperty('error'))
{
    // Handle the error here...
}
BenM
  • 52,573
  • 26
  • 113
  • 168
  • Thanks for pointing out the `hasOwnProperty` and discuss with me, It seems supported and has problems with old browsers but only DOM elements (do not inherit from object) – Khanh TO Jun 18 '13 at 10:17
0

Check the property directly

if(setRecharge[0].error!=null)//stuff for error
else //stuff for data
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
  • And what if you get this: `[{error: 0}]`? - you'll display _data_ in your alert, which is wrong. – Aleks G Jun 18 '13 at 09:24