Luarb Balla Luarb Balla - 5 months ago 22
JSON Question

Select the first JSON array child value

I want to get the value that holds the first child of a JSON array.

This is the array :

var sms = {
'1' : {
'address' : '+123',
'body' : 'SMS1'
},
'2' : {
'address' : '+123',
'body' : 'SMS2'
},
'3' : {
'address' : '+123',
'body' : 'SMS3'
},
'4' : {
'address' : '+123',
'body' : 'SMS4'
}
};


The reason is i want to loop in it to search a string using the first childs
value as it is above. Example sms.[0] = 1;

Answer

You can loop over the object using a using the in notation. Use hasOwnProperty to avoid getting references in the object

for (ii in sms) { 
  if (sms.hasOwnProperty(ii)) {
    console.log(ii, sms[ii], sms[ii]['address'], sms[ii]['body']);
  }
}
Comments