user2635299
user2635299

Reputation: 95

Creating array of objects in javascript dynamically

Am new to JavaScript,I want to create an object of following structure

var result = {
         0: {'key1' : value1,'key2' : value2 },
         1: {'key3' : value3, 'key4' : value4 },
}

Someone please help me out.Thanks in advance

Upvotes: 0

Views: 442

Answers (3)

jmventar
jmventar

Reputation: 697

The the object you posted is a JS map object,

var result = {
         0: {'key1' : value1,'key2' : value2 },
         1: {'key3' : value3, 'key4' : value4 }
}

You can access it like you access an associative array.

result[0][key1]

Or this way

result[0].key1

If you need an array of objects

  var result = [
  {'key1' : value1,'key2' : value2 },
  {'key3' : value3, 'key4' : value4 }
];

You can access it like previous example, and in this case you don't need to declare indexes.

Updated:

For map object creation you can also use a loop like @Sirko posted. The only difference is in the values assignation that could be done in this two ways:

var result  = {};
result[0] = {'key1' : value1,'key2' : value2 };
result.myOtherObj = {'key1' : value1,'key2' : value2 };

The map contents are the same as

var result = {
  0: {'key1' : value1,'key2' : value2 },
  myOtherObj: {'key1' : value1,'key2' : value2 }
};

Upvotes: 4

newpatriks
newpatriks

Reputation: 581

If you could want to create dinamically it could be a solution:

var final_result = Array();
var element_1 = {"key1" : 2,"key2" : 3};
var element_2 = {"key3" : 2,"key4" : 3};

final_result.push(element_1);
final_result.push(element_2);

Upvotes: 1

Sirko
Sirko

Reputation: 74036

Your code is valid as well, but it creates an object. If you want to use an actual array, it could look like this:

var result = [
         {'key1' : value1, 'key2' : value2 },
         {'key3' : value3, 'key4' : value4 }
    ];

Note the change from {} to [] for the outer brackets and the drop of the top-level keys.

Edit

To create such an array dynamically, you can use something like this:

var result = []; // init empty array

result.push( {'key1' : value1, 'key2' : value2 } ); // insert a value

for( var i=0; i<10; i++ ) {
  result.push( {'key1' : i, 'key2' : i } ); // insert some more values in a loop
}

Upvotes: 8

Related Questions