简体   繁体   中英

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

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
}

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 }
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM