Question: I have a JavaScript object that is treated as an associative array. Let's call it "fields". It has several elements, e.g.:

```
fields['element1'] = ...
fields['element2'] = ...
fields['element3'] = ...

```

Given fields[0], is it possible to obtain the name of the property (which is "element1") instead of its value?

Answer: 
No, for two reasons.

1. fields[0] and fields["element1"] are different properties.
2. properties in an object are explicitly unordered

You could loop over the properties:

```
function (obj) {
  for (prop in obj) {
    if (obj.hasOwnProperty(prop) {
      return prop;
    }
  }
};

```

…to get the "first" property for some arbitrary value of "first" that could change at any time.

<http://ajaxian.com/archives/fun-with-browsers-for-in-loop> explains the hasOwnProperty pattern.
There is no `fields[0]` (unless `fields` is an `Array` object, which supports numerical indices), so you can't get its name just like that. But you can simulate it like this:

```
function getKey(obj, i) {
    var j = 0;
    for (var p in obj) {
        if (j++ == i) return p;
    }
    return null;
}

```

`for (var p in obj)` will loop through every field name in the object `obj`. By getting the *n*th field name, you can effectively get the "key" for a certain index.

Note that while it's working its way to become a standard, the order of field names is currently not guaranteed according to the standards, which means that after modifying the object, the same function call could theoretically return a different field name. Same thing goes that different browsers can return different results. Practically, you'll find that just about all the browsers do keep the order of field names so you shouldn't have to worry about it at all.