1

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";
1
  • Arrays are just objects with a special length property and methods inherited from Array.prototype. The "keys" or "indexes" are standard object property names and are just numeric strings. When numbers are used as property names, they are first converted to strings, e.g. a[1] is the same as a["1"]. Commented Mar 29, 2013 at 6:29

3 Answers 3

8

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, this is an array of objects.
3

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.

Comments

1

Yes, by using objects:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.