How do I get keys from an associative array?

L

laredotornado

Hi,

Given an associative array, how do I get an array of the keys of that
associative array?

Thanks, - Dave
 
D

David Mark

laredotornado said:
Hi,

Given an associative array, how do I get an array of the keys of that
associative array?

There's no such thing as an associative array in JS.

If you mean an Object object, use a for-in loop to populate an array.
And make sure you filter the loop with either hasOwnProperty or a
similar wrapper (Google "for-in intrigue").
 
L

Lasse Reichstein Nielsen

laredotornado said:
Given an associative array, how do I get an array of the keys of that
associative array?

If arr is your associative array (i.e., an object)
In ECMAScript 5:
var keys = Object.keys(object)
In ECMAScript 3:
var keys = [];
for (var key in arr) { keys.push(key); }

/L
 
T

Thomas 'PointedEars' Lahn

Lasse said:
laredotornado said:
Given an associative array, how do I get an array of the keys of that
associative array?

If arr is your associative array (i.e., an object)
In ECMAScript 5:
var keys = Object.keys(object)
In ECMAScript 3:
var keys = [];
for (var key in arr) { keys.push(key); }

Where certain conditions must apply for the two approaches to be
equivalent, of course.

Let `o' be a reference to an object, JavaScript 1.7+ allows another
variant, Array comprehension:

var properties = [p for (p in o)];

BTW, for the property values you can use

var values = [v for each (v in o)];

there, as a combination of the ECMA-262-3 extension (v1.7+) and the
ECMA-357 implementation (v1.6+). Tested in Firefox/Iceweasel 3.5.8.


PointedEars
 
D

Dr J R Stockton

Sun said:
laredotornado said:
Given an associative array, how do I get an array of the keys of that
associative array?

If arr is your associative array (i.e., an object)
In ECMAScript 5:
var keys = Object.keys(object)
In ECMAScript 3:
var keys = [];
for (var key in arr) { keys.push(key); }

The second entry should I suppose be headed "In ECMAScript 3 & 5"; and
will then be the way to code it (for the open Web) until all browsers in
use are sufficiently ES 5 compliant.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top