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";
3 Answers 3
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).
answered Mar 29, 2013 at 4:32
Explosion Pills
192k56 gold badges341 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ted Hopp
Actually, this is an array of objects.
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.
answered Mar 29, 2013 at 4:38
chrx
3,5721 gold badge18 silver badges17 bronze badges
Comments
Yes, by using objects:
var ar = [
{ col1: "...", col2: "..." },
{ col1: "...", col2: "..." },
];
answered Mar 29, 2013 at 4:33
Petar Ivanov
93.4k11 gold badges85 silver badges95 bronze badges
Comments
lang-js
a[1]is the same asa["1"].