I would like to have a for loop create objects as the children of a parent object. Usually, I would declare the object without using the for loop like this:
var mObj = {};
mObj.obj1 = {};
mObj.obj2 = {};
mObj.obj3 = {};
mObj.obj3.firstname = "john";
mObj.obj3.lastname = "superfly";
Now lets say I would like to employ a for loop to create the children objects of a parent object "mObj".
This is where I am going wrong:
var mArr = ["firstname","lastname","email"]; // This array holds the keys for the objects
var mObj = {};
var len = (mArr.length);
for(var i=0; i<len; i++){
var obj+i = {}
mObj = obj+i;
mObj.obj + i.mArr[i] = ""
}
So the outcome of this would be:
mObj.obj1.firstname = "";
mObj.obj2.lastname = "";
mObj.obj3.email = "";
I just cannot seem to name the object with counter that is being created within for loop like:
obj1
obj2
obj3
Any help would highly be appreciated.
Thanks.
var obj+i = {} is invalid syntax.
Try this:
mObj['obj' + i] = {};
If i == 1, this gives
mObj['obj1'] = {};
Which is equiavlent to:
mObj.obj1
But when constructing dynamically, you have to use the
mObj['obj' + i]
Formatting.
var mArr = ["firstname","lastname","email"],
mObj = {},
len = (mArr.length),
i = 0;
for(; i<len; i++){
myObj['obj' + i] = {}
myObj['obj' + i].mArr[i] = ""
}
You need to use the bracket syntax to assign a dynamic variable. For example:
var sampleObj = {};
for(var j = 0; j < 3; j++)
{
sampleObj["obj" + j] = { test: j };
}
This should produce the following object:
{
"obj1" : { test: 1 },
"obj2" : { test: 2 },
"obj3" : { test: 3 }
}
After running the loop then, you could validly use this statement:
var testVal = sampleObj.obj1.test;
Related
I create multiple objects and push them to the array objArr:
var objArr = [];
var obj = {};
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
alert(objArr[i].h);
}
But as you can see, each object has the same values. Why?
Put the initialization of obj within your for-loop.
You were re-assigning new values to a global variable obj.
var objArr = [];
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var obj = {};
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
console.log(objArr[i].h);
}
Because the scope of obj in your code is global and it should rather be contained in the for loop.
If you will not declare it inside the loop then the value will get overwritten of the same obj on each iteration instead of a new memory allocation.
var objArr = [];
var height = [9, 8, 7, 3, 6, 5, 2, 4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
var obj = {};
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
console.log(obj);
As noted, you need to initialize a new object in each iteration of the loop, otherwise all your array members simply share the same object reference.
Additionally, your code can be greatly reduced by building the array using .map(), and fully using the object literal initializer to declare the properties.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((n, i) => ({h: n, index: i}));
console.log(objArr);
This is shorter and clearer. For every number in height, it creates a new object and adds it to a new array, which is returned from .map().
It can be even a little shorter with the newer features for object literals.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((h, index) => ({h, index}));
console.log(objArr);
I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:
//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?
You have to move the object inside the loop.
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
var NewIssue = {};
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
myFunction();
console.log(newIssueList);
And then you could just extend the object literal a but to make it much more readable:
for (var i = 0; i < 3; i++) {
var NewIssue = {
Id:i,
Number:233+i,
Name:"Test"+i
};
newIssueList.push(NewIssue);
}
You can also avoid using a superfluous var by creating an inline object:
newIssueList.push({
Id: i,
Number: 233 + i,
Name: "Test" + i.toString()
});
There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.
You need to create a new object on every iteration.
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
newIssueList.push({
id: i,
number: 233 + i,
name: "Test" + i.toString()
});
}
}
myFunction();
console.log(newIssueList);
I'm making a javascript neural network and trying to put some entries into an object using for loops but I'm not getting the result I want.
I want to be able to get an object looking like:
{0 : {neuron1Sum : null}}
And I want to loop it to create multiple neurons and layers. It might be easier to understand once you see the code.
hiddenLayers : function() {
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer = {};
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i] = ["neuron" + j + "Sum"];
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
},
Your hiddenLayer should be defined as array and hiddenLayer[i] should be defined as object. Then put each element to object like this way.
hiddenLayers : function() {
var hiddenLayer = []; // defined as array
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = {}; //defined as object
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
return hiddenLayer;
/*
will return something like :
[
0 : {neuron1Sum : null, neuron2Sum : null},
1 : {neuron1Sum : null, neuron2Sum : null}
]
*/
},
Looks like you need to move a couple identifiers around and initialise an Array before the inner loop
// ...
hiddenLayers: function() {
var numberOfNeurons,
hiddenLayer = [], // keep this across all the loops
temp, // to store objects as we make them
i, j;
for (i = 0; i < arguments.length; ++i) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = []; // remember to initialise
for (j = 0; j < numberOfNeurons - 1; ++j) {
temp = {};
temp["neuron" + j + "Sum"] = null;
hiddenLayer[i].push(temp);
}
}
return hiddenLayer; // remember to return
},
// ...
This code now produces something like
[
[
{neuron0Sum: null},
{neuron1Sum: null}
],
[
{neuron0Sum: null},
{neuron1Sum: null}
]
]
Starting in ES6 we will be able to use expressions in the property names of Object literals, e.g.
{
["foo" + "bar"]: "baz"
}
// produces
{
"foobar": "baz"
}
If you want your code to work in production right now, don't use this feature yet (maybe in a year or two)
I don't think that code is doing what you want, but I'm not sure what you want..
This assignment:
hiddenLayer[i] = ["neuron" + j + "Sum"];
sets hiddenLayer[i] to an array containing a single string. It's equivalent to this:
hiddenLayer[i] = [];
hiddenLayer[i][0] = "neuron" + j + "Sum";
Then this assignment:
hiddenLayer[i]["neuron" + j + "Sum"] = null;
Treats hiddenLayer[i] as a generic Object (associative array, map, hash, dictionary) and sets a named property (with the same name as that string) to null. So if i is 0 and j is 0, you get an object that looks like this:
{
0: "neuron0Sum",
neuron0Sum: null
}
I suspect that's not what you're trying to accomplish...
So, I have an array of objects like this:
for(var i=0; i<travelcard_table.length;i++){
var table_row = travelcard_table.eq(i);
var ii = 0;
passenger_info[i] = {};
table_row.find("td").each(function() {
passenger_info[i][table_keys[ii]] = $(this).text();
ii++;
});
}
passenger_info[0]['First name'] = "John"; etc..
passenger_info[1]['First name'] = "Chuck"; etc..
Im trying to split this to smaller arrays of objects every 10 entries, so Its something like this:
var size = 10;
for (var i=0; i<passenger_count; i+=size) {
var smallarray = passenger_info.slice(i,i+size); << "Error: Slice is not a function"
console.log(smallarray);
// do something with smallarray
}
How to achieve this?
var passenger_info = [[], []];
passenger_info[0]['First name'] = "John";
passenger_info[1]['First name'] = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0]['First name']);
This alerts 'John', because passenger_info is an Array of Array objects and you are attaching properties to the array object and not to its items.
for an array of objects it should be:
var passenger_info = [ {} , {}];
passenger_info[0].firstname = "John";
passenger_info[1].firstname = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0].firstname);
like this you can workout
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [];
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
smallArray.push(passenger_info[i+j]);
}
console.log(smallArray);
}
for using slice you can do like this
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [],ls;
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
ls = i+j;
}
smallArray = passenger_info.slice(i,ls+1);
console.log(smallArray);
}
How can I refer to an object element dynamically during a loop by using an array, something like this:
var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
ol.push( lvl[l] )
obj[ol] = 'someval'
}
so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.
Not sure if I have explained that very well ?!
Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.
var obj = {};
var lvl = ['x','y','z'];
var ol = {};
for (var i = 0; i < lvl.length; i++){
obj[i] = {};
ol = obj[key];
}
You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:
var obj = {};
var levels = ['x','y','z'];
var pointer = obj;
for (var l=0; l<levels.length; l++) {
key = levels[l];
if (l < levels.length-1) { // if not last element
pointer[key] = {};
pointer = pointer[key];
}
else { // if last element
pointer[key] = 'someval';
}
}
console.log(obj); // should log {x:{y:{z:"someval"}}}