Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new object instances in a loop

Tags:

javascript

I'm trying to create a new object for each item in an array by looping. The names of the objects should be based on the key of the array.

So for this array:

var arr = new Array(
    "some value",
    "some other value",
    "a third value"
);

Would result in three objects:

alert(object1.value);
alert(object2.value);
alert(object3.value);

The code I have thus far (but isn't working) is:

// Object
function fooBar(value) {
    this.value = value;
    ...
}

// Loop
var len = arr.length;
for (var i = 0; i < len; i++) {
    var objectName = object + i;
    var objectName = new fooBar(arr[i]);
}

Does what I'm asking for even make sense?

like image 933
Phil Avatar asked Jan 05 '13 23:01

Phil


2 Answers

You have to make an array of the objects also

var objs = new Array();

for(var i = 0; i < len; i++) {
  objs[i] = new fooBar(arr[i]);
}

alert(objs[0].value);
like image 147
u8sand Avatar answered Oct 05 '22 23:10

u8sand


You can map your array:

var arr = new Array(
    "some value",
    "some other value",
    "a third value"
);
var fooBars = arr.map(function(x) { return new fooBar(x); });

Then you can access each value:

alert(fooBars[0].value);
// etc.

or process them all at once:

fooBars.forEach(function (foo) { alert(foo.value); });
like image 44
Ted Hopp Avatar answered Oct 05 '22 23:10

Ted Hopp