6

Possible Duplicate:
Access the first property of an object

I have a javascript object like this:

var list = {
    item1: "a",
    item2: "b",
    item3: "c",
    item4: "d"
};

Using reflection in JS, I can say list["item1"] to get or set each member programmatically, but I don't want to rely on the name of the member (object may be extended). So I want to get the first member of this object.

If I write the following code it returns undefined. Anybody knows how this can be done?

var first = list[0]; // this returns undefined
Community
  • 1
  • 1
Mo Valipour
  • 13,286
  • 12
  • 61
  • 87

4 Answers4

41
 for(var key in obj) break;
 // "key" is the first key here
user187291
  • 53,363
  • 19
  • 95
  • 127
11
var list = {
    item1: "a",
    item2: "b",
    item3: "c",
    item4: "d"
};

is equivalent to

var list = {
    item2: "b",
    item1: "a",
    item3: "c",
    item4: "d"
};

So there is no first element. If you want first element you should use array.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • That's right, but stereofrog's answer gives me what I want!. I wouldn't say "there is no first", I would say "there is no ordering or indexing on object members". Anything coming first is first any way. – Mo Valipour Sep 25 '11 at 11:39
  • @valipour: So why does your question say *"I want to get the first member of this object"* if you don't care if you get the first item as defined by your ordering? Now it sounds like you're actually asking for a single member, irrespective of the order you defined. – user113716 Sep 25 '11 at 12:49
2

Even though some implementations of JavaScript uses lists to make object, they are supposed to be unordered maps.

So there is no first one.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
megakorre
  • 2,213
  • 16
  • 23
  • 2
    That's right, but stereofrog's answer gives me what I want!. I wouldn't say "there is no first", I would say "there is no ordering or indexing on object members". Anything coming first is first any way. – Mo Valipour Sep 25 '11 at 11:40
0

How do I loop through or enumerate a JavaScript object?

You can use the following to get the desired key.

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}

You need to use an array if you want to access elements in an indexed way.

Community
  • 1
  • 1
Jack
  • 15,614
  • 19
  • 67
  • 92