Hi George,
(It's a JavaScript rather than Prototype/script.aculo.us question,
yes.)
This object literal / JSON data:
[{bookingref:'A6D98FGR', canceled:0}]
...defines an array with a single element, which is an object instance
with two properties: bookingref (value 'A6D98FGR') and canceled
(value 0).
You can get the values just by referring to the properties of the
object, so:
var x = RS[0].bookingref;
alert(x); // Alerts 'A6D98FGR'
JavaScript allows you to use property names both literally with dot
notation (as above), and _also_ via string names using bracket
notation; we could write the above like this instead:
var x = RS[0]['bookingref'];
alert(x); // Alerts 'A6D98FGR'
Note the quotes, the square brackets, and the absense of the dot.
If you don't know the names of the properties in advance, you can use
the for..in loop to iterate over the names of the object's properties:
var name;
for (name in RS[0]) {
alert(name + '=' + RS[0][name]);
}
In the loop, the variable 'name' is set on each iteration to the name
of a property on the object, as a string. This is powerful when
combined with bracket notation. On the object defined in your JSON
above, that will show "bookingref=A6D98FGR" and "canceled=0"; the
order is not defined and almost certainly will vary from
implementation to implementation.
Note that for..in is for iterating over the properties of an object,
*not* the elements of an array. Many JavaScript programmers think
it's for the latter, and they get into trouble as a result because
Prototype adds some properties to arrays that they're not expecting to
see. Details:
http://proto-scripty.wikidot.com/prototype:tip-looping-through-arrays
But again, it's totally fine for looping through the properties on an
object, like your RS[0].
HTH,
--
T.J. Crowder
tj / crowder software / com
On Dec 5, 12:18 pm, George <[EMAIL PROTECTED]> wrote:
> Hi Folks,
>
> This may be more of a pure JavaScript question than Prototype, but
> here goes:
>
> If I have a JSON array called RS for example containing this:
> [{bookingref:'A6D98FGR', canceled:0}]
> is there a way for me to programatically get the names and values?
>
> I'd like to be able to do something like
> RS[0].[0].name ((would be 'bookingref'))
> RS[0].[0].value ((would be 'A6D98FGR'))
>
> I hope that makes sense.
>
> Many thanks
>
> George
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Prototype & script.aculo.us" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---