How to get first member of an object in javascript [duplicate]

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

Answers:

Answer
 for(var key in obj) break;
 // "key" is the first key here
Answer
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.

Answer

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

So there is no first one.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.