sundeep kumar
sundeep kumar

Reputation: 13

associative array conundrum in javascript

In javascript I can 'create' an associative array by initializing a javascript object via JSON

eg var bArr = {"key1": "val1","key2": "val2", "key3": "val3"}

then access the array elements like bArr["key1"], bArr["key2"], bArr["key3"].

However instead of initialization with JSON can we somehow just index elements like bArr["key1"] in a loop and assign them values individually ?

Upvotes: 1

Views: 51

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50674

You can initialize values into your javascript object by doing bArr["key"] = "value";. Doing this will give you:

bArr = {
  "key": "value"
}

Thus, using a loop, you can concatenate i to the end of your key and value to generate your object which has keys from 1 to n and values from 1 to n, where n is an integer (of limited size):

var bArr = {};

for(var i = 1; i <= 3; i++) {
  bArr["key" +i] = "val" + i;
}

console.log(bArr);

Upvotes: 1

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

yes you can. very simple actually:

var obj = {};

for (var i = 0; i < 10; i++) {
  obj['val' + i] = i;
}

console.log(obj);

Upvotes: 1

Related Questions