Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic object in a loop?

Basically I want to create one large object of many object in JavaScript. Something like:

var objects = {} for (x) objects.x = {name: etc} 

Any ideas?

like image 699
mike Avatar asked Mar 04 '10 23:03

mike


People also ask

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

How do I create a dynamic object in node JS?

To create a dynamic object in a loop with JavaScript, we can use the square bracket notation to add properties to an object dynamically. We create an empty object and assign it to the objects variable. Then we add a for loop that loops through some numbers. And we use the numbers as property names with objects[x] .

How do you create a dynamic object in C++?

A dynamic object is created using a "new" operator that returns a pointer to the newly constructed object and is destructed by a "delete" operator. A pointer variable is used to hold the pointer to the object that is returned by the "new" operator.


2 Answers

var objects = {};  for (var x = 0; x < 100; x++) {   objects[x] = {name: etc}; } 
like image 101
Tomalak Avatar answered Sep 23 '22 21:09

Tomalak


An actual implementation

Populate a container object with 100 other objects.

<script> var container = { }; // main object  // add 100 sub-object values for(i = 0; i < 100; ++i) {  container['prop'+i ]  /*property name or key of choice*/          = { 'a':'something',               'b':'somethingelse',               'c': 2 * i            };  } 

TEST THE Results - iterate and display objects...

for(var p in container) {  var innerObj = container[p];  document.write('<div>container.' + p + ':' + innerObj + '</div>');  // write out properties of inner object  document.write('<div> .a: ' + innerObj['a'] + '</div>');  document.write('<div> .b: ' + innerObj['b'] + '</div>');  document.write('<div> .c: ' + innerObj['c'] + '</div>'); } </script> 

Output is like

container.prop0:[object Object] .a: something .b: somethingelse .c: 0 container.prop1:[object Object] .a: something .b: somethingelse .c: 2 container.prop2:[object Object] .a: something .b: somethingelse .c: 4 

etc...

like image 42
John K Avatar answered Sep 20 '22 21:09

John K