noushad
noushad

Reputation: 175

Javascript Array with String Key

Is it possible in JavaScript create a array with string Key.?

eg:-

arr[0]['col1']="Firstname";
arr[0]['col2']="Lastname";

arr[1]['col1']="firstname1";
arr[1]['col2']="lastname2";

Upvotes: 1

Views: 6413

Answers (3)

Explosion Pills
Explosion Pills

Reputation: 191749

Yes, but it's called an object, not an array.

arr = [{col1: 'Firstname', col2: 'Lastname'},
    {col1: 'Firstname', col2: 'Lastname'}];

You can access (assign or retrieve) the values by arr[0]['col1'] and even arr[0].col1.

EDIT: For clarification the data structure that looks like an array with string keys is called an object. This example is still using an array (with numeric keys).

Upvotes: 8

chrx
chrx

Reputation: 3572

You'll most likely want to use an object literal:

var studentAges = {
  sara: 14,
  mike: 17,
  daniel: 15,
  Jake: 14
};

There are no associate arrays in JavaScript.

Upvotes: 3

Petar Ivanov
Petar Ivanov

Reputation: 93030

Yes, by using objects:

var ar = [
    {  col1: "...", col2: "..." },
    {  col1: "...", col2: "..." },
];

Upvotes: 1

Related Questions