Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 609
Mo Valipour Avatar asked Sep 25 '11 11:09

Mo Valipour


People also ask

How do I find the first element of an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.

How do you get the first value in a an array of objects?

Get first element of an array shift() and filter() Within the filter() method, the code will check if the element is undefined or not. Only if the element is not undefined will the shift() method be applied to it to retrieve the first element.

Can JavaScript object have duplicate keys?

In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.


1 Answers

 for(var key in obj) break;
 // "key" is the first key here
like image 127
user187291 Avatar answered Oct 10 '22 22:10

user187291