views:

76

answers:

4

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?

+1  A: 
var objects = {};

for (var x = 0; x < 100; x++) {
  objects[x] = {name: etc};
}
Tomalak
Why not use an array?
Eli Grey
Bacause the OP wants "one large object of many object".
Tomalak
A: 

From what I'm understanding you would like to save multiple {name: etc} into on large object then that means that your looking at an array.

var objects = new Array();

for(x)
{
    objects.push(name: etc);
}

as for whats in the brackets of the for loop that all depends on what you are looking to do exactly.

Jonathan Czitkovics
I see two major blaring syntax errors in your code. No offence, but I think you should learn JS first before trying answer questions on it.
Eli Grey
I knew that there were errors but I was going based on what I was understanding from him. I did not notice that I could comment on his original question cause then I would have asked for some clarification.
Jonathan Czitkovics
A: 

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...

John K
A: 

Try this

var objects = new Array();
var howmany = 10;

for(i=0;i<howmany;i++)
{
    objects[i] = new Object();

}
streetparade
You have a leaking global `i` variable. Don't forget to use `var`.
Eli Grey