build objects in for loop with javascript - javascript

I am trying to dynamically build an object for every iteration of a for loop using the i as part of the object name. based on the example below I would like 19 objects with names: obj0, obj1, obj2... obj18.
so I have an array with a length:
console.log(foo.length); // 19
for (var i = 0; i < foo.length; i++) {
var bar+i = {};
};
console.log(bar1);
console.log(bar2);
// ...
console.log(bar18);
I can't figure out the correct syntax for "var bar+i = {};", obviously it does not work.
EDIT
I really need objects because I am constructing data to be used in D3.js that needs to be an array of many objects

Unless bar{i} is an array value / object property itself the only way to do this is to bind it to the window or root object.
window[bar+i] = {};
Or to the root object
this[bar+i] = {};
Much better to bind it to an array / object itself though rather than bind senselessly to the root/window.
var array = [];
array[bar+i] = {};

There are some hacks how you can achieve this. However I advice you to use arrays instead of that method you are trying to use:
console.log(foo.length); // 19
var variables = [];
for (var i = 0; i < foo.length; i++) {
variables[i] = {};
};
console.log(variables[0]);
console.log(variables[1]);
// ...
console.log(variables[18]);

You can't create variables like this.
What you can do is add properties of the global scope, which you can use as variables:
for (var i = 0; i < foo.length; i++) {
window['bar'+i ] = {};
};
or use another object to hold everything:
var container = {};
for (var i = 0; i < foo.length; i++) {
container['bar'+i] = {};
};

You can't dynamically write variable names, but you can do the same on object properties:
console.log(foo.length); // 19
var obj = {};
for (var i = 0; i < foo.length; i++) {
obj[ 'bar' + i ] = {};
};
console.log(obj.bar1);
console.log(obj.bar2);
// ...
console.log(obj.bar18);

You can use eval:
eval('var bar'+i+' = {};');
But really, you shouldn't be doing this, unless you know for sure you can't do it the other way.

Related

Assigning value to function as object property within for loop

I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.
When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.
var array = [];
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}
However, when I call the value held in that property (i.e.):
console.log(array[2].someFunction)
It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.
Basically you had some problems in your code, like:
not defining number
using var instead of let
not defining the object
using the same value as parameter of the function
here you have the working solution.
var array = [];
// numbers was not defined.
const number = 10;
// use let instead of var
for (let i = 0; i < number; i++) {
// you are not instantiating your object, here is an example.
array[i] = {
"foo": "bar",
"index": i,
}
// you have to change i to j, because if you use i
// it will be the parameter of the function
array[i].someFunction = function(j) {
console.log('index: ', i);
console.log('parameter: ', j)
}
}
// we see the function
console.log(array[2].someFunction)
// we call the function succesfully
array[2].someFunction(100);
It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:
var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
array[i].index = i;
array[i].someFunction = function(){console.log(this.index);}
}
//and see that it's working...
for(var i = 0; i < array.length; i++){
array[i].someFunction();
}

Create multiple variables inside for loop

I am trying to create multiple new variables inside a loop.
The number of new variables depends on the lenght of another variable (variable "list" used below).
for(var i = 0; i < list.lenght; i++)
{
var counter + i; // create new variable (i.e. counter1, counter2,...)
}
I found a lot of very simmilar questions on StackOverflow, and the answer is mostly using an array (i.e. How do I create dynamic variable names inside a loop?).
If I use the suggested solution, do I create an array of variables? So in my case I will create multiple counters and I can then add values to that variables, i.e.:
counter6++;
If that is not the case how could I tackle the problem?
I apologize for asking you to explain an old answer, but I cannot comment in the old one because of low reputation.
You have some options here :
Create them global (not best practice ) :
for(var i = 0; i < list.lenght; i++){
window['counter' + i] = 0; // create counter1, counter2,...)
}
Use object :
var scope = {};
for(var i = 0; i < list.lenght; i++){
scope['counter' + i] = 0; // create scope.counter1, scope.counter2,...)
}
Use Object with with keyword
var scope = {};
for(var i = 0; i < list.lenght; i++){
scope['counter' + i] = 0; // create scope.counter1, scope.counter2,...)
}
with(scope){
// here you can acesess keys in the scope object like them variable on the function scope
counter0++
}
Use plain old Array
var scope = new Array(list.length);
You can create an object, set property names to expected variable names, then use object destructuring assignment to get the property assignment or index of an object having a .length as a variable identifier; or use array destructuring to assign an identifier to a specfic index.
let [list, obj] = ["abc", {}];
for (let i = 0; i < list.length; i++) {
obj["counter" + i] = list[i]
}
let {counter0, counter1, counter2} = obj;
console.log(counter0, counter1, counter2);
Alternatively
let list = "abc";
let {0:counter0, 1:counter1, 2:counter2} = list;
console.log(counter0, counter1, counter2);
let list = ["a","b","c"];
let [counter0, counter1, counter2] = list;
console.log(counter0, counter1, counter2);

How to create a multidimensional array in JavaScript?

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Javascript prototype from instance

I would like to make objects, with earlier created objects as the prototypes. This way I would be able to make additions to existing objects without modifying them.
Methods which interact with the earlier created objects (so using there attributes and perhaps mutating them) could also be applied to the newly derived objects.
I thought this could be done with the following code, but it doesn't...
objs = [];
for (var i = 0; i < 5; i++) {
objs.push({
index: i
});
}
for (var i = 0; i < 5; i++) {
var newObj = {};
newObj.prototype = objs[i];
alert(newObj.index);
}
http://jsfiddle.net/q5bu25L1/2/
A prototype comes into play when you use a constructor to create an instance of an object. In order to get your approach to work, you can do this:
for (var objI in objs) {
var obj = objs[objI];
var newObj = function() {};
newObj.prototype = obj;
newObj = new newObj();
console.log(newObj.i);
}
http://jsfiddle.net/q5bu25L1/3/
Or you could just use Object.create(), which accomplishes pretty much the same thing.
Note that neither of these approaches can completely prevent the contents of the parent objects from being modified if they themselves contain objects. For example:
var a = { n: 8, myObj: { i: 7 }};
var b = Object.create(a);
b.n = 10;
console.log(a.n); // still 8
console.log(b.n); // 10
b.myObj.i = 15;
console.log(a.myObj.i); // changed to 15!
console.log(b.myObj.i); // 15
http://jsfiddle.net/0f5ydL6u/
what about using native Object.create() ECMA5 spec
look at the full support comparison
objs = [];
for (var i = 0; i < 5; i++) {
objs.push({
index: i
});
}
for (var i = 0; i < 5; i++) {
var newObj = Object.create(objs[i]);
alert(newObj.index);
}
DEMO

Javascript Dynamic Arrays and Object

Is this possible?
So I need to have an array with a dynamic name and content what can be extended and accessed.
object = {};
var two = ['thing', 'thing2'];
for(one in two){
object[two[one]] = [];
}
If yes but not in this way, then how?
This is definitely doable, just make sure that the object owns the property and it's not inherited from higher up in the prototype chain:
object = {};
var two = ['thing', 'thing2'];
for..in:
for(var one in two){
if(two.hasOwnProperty(one))
object[two[one]] = [];
}
for:
for(var i = 0; i < two.length; i++)
object[two[i]] = [];
var object = {};
var props = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
object[props[i]] = [];
}

Categories