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);
Related
Push items on to "entrants" array not working. Anybody know why?
<script>
function taz() {
var entrants = [];
for (var i = 1; i <= 48; i++) {
entrants.push('#P' + i);
}
return entrants;
alert(entrants.length);
console.log(taz());
}
</script>
If you absolutely need the keys to be named, you're looking for an object rather than an array.
function taz() {
var entrants = {};
for (var i = 1; i <= 48; i++) {
entrants['P' + i] = 'Some Value' + i;
}
return entrants;
}
console.log(taz());
However, it might make more sense to store the data in an array, in which case you wouldn't have named keys.
function taz() {
var entrants = [];
for (var i = 1; i <= 48; i++) {
entrants.push('Some Value' + i);
}
return entrants;
}
console.log(taz());
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...
I need to implement DataTable struct ,that is in c#, in javascript.
For example
function Servers(name)
{
this.Name = name;
this.Columns = new Array(5);
var rows = new Array(3);
for (var i=0;i<3;i++)
rows[i]=new Array(5);
this.Rows = rows;
}
I simply access jth element of ith Row by typing like this;
Servers.Rows[i][j]
This works good, but I need to call my object like this;
Servers.Rows[i]["ServerUrl"]
But I dont know how to implement a prototype for this work.
Is there anyway to achieve this?
Note: Columns array holds Column names like in c# and Columns array size always equals to Rows' sub array.
Live demo
function create2Array(d1, d2, fn) {
var arr = [],
d = function(x, y) {},
f = fn || d;
for (var i = 0; i < d1; i++) {
for (var j = 0, curr = []; j < d2; j++) {
curr[j] = f.call(window, i, j);
};
arr[i] = curr;
};
return arr;
};
function createArrayOfObjects(d1) {
var arr = [];
for (var i = 0; i < d1; i++) {
arr[i] = {};
};
return arr;
};
function print2DArray(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + arr[i].join(" ") + "</p>";
};
};
function printArrayOfObj(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + JSON.stringify(arr[i]) + "</p>";
};
};
var Server = {};
Server.Rows = createArrayOfObjects(10);
Server.Rows[0]["something"] = "test";
printArrayOfObj(Server.Rows);
Use it like this:
Server.rows = create2Array(10, 10);
Or you can even specify a custom init function which takes the index as param.
Say if you want to init your matrix with 0 by default:
Server.rows = create2Array(10, 10, function(x, y) { return 0;});
Or if you use an object.
Server.rows = create2Array(10, 10);
Server.rows[0]["ServerUrl"] = "test";
You should use a hash/object for this.
If you want to refer to variables in a data structure by name/string in javascript the an object is the best option. See here: https://developer.mozilla.org/en/docs/JavaScript/Guide/Working_with_objects
function Qnt_Box(e) {
var app = UiApp.getActiveApplication();
var Vpanel = app.getElementById('Vpanel');
app.getElementById('button2').setVisible(false);
var qnt = e.parameter.Quant;
var grid2 = app.createGrid(qnt, 2);
for (var i = 0; i < qnt ; i++) {
grid2.setWidget(i, 0, app.createLabel(i + 1 + ' :'));
grid2.setWidget(i, 1, app.createTextBox().setName('x' + i)); HERE!!!
}
Vpanel.add(grid2);
return app;
}
How do I load the variables, which were named in a looping, looping one another?
My Idea was:
function example() {
for(var i =0; i < qnt+1; i++)
var aux = e.parameter.'x' + i;
}
but not work XS
Thank you!!
If the name is in a property of e.parameter, you can use Bill's suggestion
e.parameter['x' + i];
If it's a global variable, you can access it through the window object
window['x' + i]
I don't completely follow your code, but if you are trying to access a property using a variable name, you can use array notation.
function example() {
for(var i =0; i < qnt+1; i++)
var aux = e.parameter['x' + i];
}
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;