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
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.
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.
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.
for(var key in obj) break;
// "key" is the first key here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With