Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with

array['serial_number'] = 'value'

serial_number and value are strings. e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine. Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array. How do I do it? I can't think I need an iteration with

for (var i in sorted)

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

like image 560
transient_loop Avatar asked Dec 20 '10 15:12

transient_loop


2 Answers

2021 Update

Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:

Original answer

JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:

var nameValues = [
    {name: '20910930923', value: '20101102'},
    {name: 'foo', value: 'bar'}
];

... or as an ordered list of property names to use with your existing object:

var obj = {
   '20910930923': '20101102',
   'foo': 'bar'
};

var orderedPropertyNames = ['20910930923', 'foo'];
like image 97
Tim Down Avatar answered Sep 18 '22 13:09

Tim Down


Try this:

// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};

// First element (see attribution below)
return offers[Object.keys(offers)[0]];

// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
like image 38
psimons Avatar answered Sep 18 '22 13:09

psimons