Hi,

Regardless of where the object came from (having evaluated it from a
JSON string or something else), that's what "for..in" is for:

    var name, obj = "{'a': 1, 'b': 2}".evalJSON();
    for (name in obj) {
        alert(name + "=" + obj[name]);
    }

...alerts "a=1" then "b=2".  The order is not guaranteed.  Cool, eh?

Speaking generally, "for..in" iterates through the names of the
properties in the object.  Note that depending on the object in
question, some of those properties may refer to functions:

    var obj = {
        foo: function() {
            alert("Foo!");
        },
        bar: 42
    };
    var name;
    for (name in obj) {
        alert("typeof obj[" + name + "] = " + typeof obj[name]);
    }

...alerts "obj[foo] = function" and "obj[bar] = number".

"for..in" includes properties an object has inherited from its
prototype:

    var a = ['one', 'two'];
    var name;
    for (name in a) {
        alert("typeof a[" + name + "] = " + typeof a[name]);
    }

...will not only alert "a[0] =one" and "a[1] = 2" but also any other
enumerable properties on arrays.  In most implementations, there
aren't any other *enumerable* properties (some properties can be
marked "dontEnum", but only by the implementation, not our code), but
when you're using Prototype, there are lots -- because Prototype adds
lots of properties to the Array prototype referencing additional nifty
Array functions.  Which is why you don't use "for..in" to loop through
array elements, there could be more than just the array elements.[1]

You can filter out the properties that are inherited from the
prototype by using hasOwnProperty:

    var a = ['one', 'two'];
    var name;
    for (name in a) {
        if (a.hasOwnProperty(name)) {
            alert("typeof a[" + name + "] = " + typeof a[name]);
        }
    }

...will only alert the two you expect.

All of the above is JavaScript, not Prototype; details in the spec[2].

[1] http://proto-scripty.wikidot.com/prototype:tip-looping-through-arrays
[2] http://www.ecma-international.org/publications/standards/Ecma-262.htm

HTH, have fun!
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available


On Aug 10, 2:54 pm, krishna81m <krishna...@gmail.com> wrote:
> I tried to google and search prototype API for a method that will give
> me just the keys in a JSON object.
>
> Is there none in Prototype and no way to know the keys?
>
> Regards
> Krishna
--~--~---------~--~----~------------~-------~--~----~
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 prototype-scriptaculous@googlegroups.com
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to