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
3
  • stackoverflow.com/questions/2342371/… Commented Sep 25, 2011 at 11:30
  • But what if you change the code that initialises that object. Surely it's better to reference it by name, or use an array? Commented Sep 25, 2011 at 11:34
  • @Jack: I'm not looking for a loop Commented Sep 25, 2011 at 11:34

4 Answers 4

41
 for(var key in obj) break;
 // "key" is the first key here
Sign up to request clarification or add additional context in comments.

1 Comment

That's a very smart solution.
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.

2 Comments

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.
@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.
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.

1 Comment

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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.