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?
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);
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With