This question already has answers here:
Push is overwriting previous data in array
(2 answers)
Closed 4 years ago.
For few hours now I been trying to hack this but I really cant seem to succeed. I am trying to create a JSON string as below, but when passing the values of the variable obj to variable j I am getting an array of only the last result of that loop.
instead of getting results such as:
[{machine: "hi"...}
{machine: "2"....}]
I am getting:
[{machine: "2"...}
{machine: "2"....
and keep going with same value}]
What am I doing wrong?
var return_json = function(){
var j = [];
var obj = {};
var td;
for(var i=1;i<tr.length;i++){
td = tr[i].getElementsByTagName("td");
obj['machine'] = td[0].innerHTML;
console.log(obj['machine']);
obj['day'] = td[1].getElementsByTagName("p")[0].innerHTML;
obj['night'] = td[2].getElementsByTagName("p")[0].innerHTML;
j.push(obj);
console.log(j);
}
return j;
};
console.log(save_limitation());
You're only creating a single object instance in obj variable before the loop. In every iteration, you update the properties of the object and push the same object into your array.
To fix it, create a new object within your loop at every iteration.
var return_json = function() {
var j = [];
var td;
for(var i = 1; i < tr.length; i++){
td = tr[i].getElementsByTagName("td");
j.push({
machine: td[0].innerHTML,
day: td[1].getElementsByTagName("p")[0].innerHTML,
night: td[2].getElementsByTagName("p")[0].innerHTML
});
}
return j;
};
Try initalise the td and obj inside the loop for every element:
var return_json = function(){
var j = [];
for(var i=1;i<tr.length;i++){
var obj = {};
var td;
td = tr[i].getElementsByTagName("td");
obj['machine'] = td[0].innerHTML;
console.log(obj['machine']);
obj['day'] = td[1].getElementsByTagName("p")[0].innerHTML;
obj['night'] = td[2].getElementsByTagName("p")[0].innerHTML;
j.push(obj);
console.log(j);
}
return j;
};
console.log(save_limitation());
obj.machine is a reference to td. You need to remove the link to the td once it is assigned. This should solve it.
for(var i=1;i<tr.length;i++){
td = {};
td = tr[i].getElementsByTagName("td");
obj['machine'] = JSON.parse(JSON.stringify(td));
console.log(obj['machine']);
obj['day'] = td[1].getElementsByTagName("p")[0].innerHTML;
obj['night'] = td[2].getElementsByTagName("p")[0].innerHTML;
j.push(obj);
console.log(j);
}
Because obj is defined outside of the loop you are adding the same object to the array each loop. You are updating the properties of obj on every iteration.
Define obj inside of the loop to ensure you are not doing this.
var tr = document.getElementById("myTable").getElementsByTagName("tr");
var return_json = function(){
var j = [];
for(var i=1;i<tr.length;i++){
var obj = {};
var td = tr[i].getElementsByTagName("td");
obj['machine'] = td[0].innerHTML;
obj['day'] = td[1].getElementsByTagName("p")[0].innerHTML;
obj['night'] = td[2].getElementsByTagName("p")[0].innerHTML;
j.push(obj);
}
return j;
};
console.log(return_json());
<table id="myTable">
<tr><td>Machine</td><td>Day</td><td>Night</td></tr>
<tr><td>1</td><td><p>1d</p></td><td><p>1n</p></td></tr>
<tr><td>2</td><td><p>2d</p></td><td><p>2n</p></td></tr>
<tr><td>3</td><td><p>3d</p></td><td><p>3n</p></td></tr>
</table>
Related
I have a JS function with for loops. Inside the nested for loops, str element prints all of the intended elements. But, outside it doesn't print all of it. I would appreciate any help. Here is my code:
function getResearchersFullName(allDataJson){
var str = [];
var myarr = [];
var c = 0;
for(var i = 0; i < allDataJson.length; i++){
myarr[i] = allDataJson[i].Researchers.split(", ");
for(var j = 0; j < myarr[i].length; j++){
str[c] = myarr[i][j];
//console.log(str[c]); //prints as expected
}
}
return str;
}
I am trying to use the returned value as follows but it only prints one of the str values.
var fullnames = getResearchersFullName(allDataJson);
for(var i = 0; i <fullnames.length; i++){
console.log(fullnames[i]); //returns only 1 object
}
Your code never increments c. The only element of str that's ever modified is element 0.
Use str.push(myarr[i][j]); and you won't need c at all.
How to have object inside of an Array and Iterate to access Objects one by one.
Please help to solve this.
var mainVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var hubVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var posit = {1:mainVals,2:hubVals};
for (var i = 1;i <= 2;i++)
{
var obj = posit.i;
alert("obj:"+obj); // which gives undefined
}
You need to use square-bracket notation when the property you're wanting to read is dynamic:
var obj = posit[i];
The correct code should be something like this, since you have two arrays inside of each other:
var mainVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var hubVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var posit = {1:mainVals,2:hubVals};
for (var i = 1;i <= 2;i++)
{
for(var j = 0; j <= 1; ++j){
var obj = posit[i][j];
alert("obj:"+obj);
}
}
I have a for loop in which I am getting all the values one by one but I need to form those values into one array.
Can any one let me know how to get form all the values into one array.
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
var yourArray = [];
yourArray.push(marray);
console.log(marray);
}
Output getting from the above code is : ["0123"] and ["3456"]
But the expected output is ["0123","3456"]
You are creating a new yourArray for each loop iteration. Instead of doing that, create it just once before starting the loop:
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
Note that I have changed the code to read yourArray.push(mId) because from the question it seems that's what you want -- not yourArray.push(marray).
A more compact way of doing the same is to use the array map function like this:
var yourArray = marray.map(function(row) { return row.id; });
This last version won't work out of the box in IE 8, so if you care about that you need to take appropriate measures.
decalare variable in outside for loop..
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mid);
}
console.log(yourArray);
Initialise yourArray before the loop
Try this
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
The var yourArray is initialized to null each time you enter the loop. Define it outside loop.
How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript expression to define object’s property name?
I'm trying to add objects to an array, but I want to have the name and value to be dynamic. Here's an example:
(function(){
var data = [];
for(i=0; i<5; i++){
data.push({'name' + i: i});
}
console.log(data);
})()
I guess I can't use a variable for the property so I'm not sure what to do.
If you want to use a dynamically named property, you need to use array access notation:
var temp = {};
temp['name' + i] = i;
data.push(temp);
In the IIFE:
(function(){
var data,
temp,
i;
data = [];
for (i = 0; i < 5; i += 1) {
temp = {};
temp['name' + i] = i;
data.push(temp);
}
console.log(data);
}());
Modified code: key based on variable value can be added in an object using '[]'. jsfiddle
(function(){
var data = [], a;
for(i=0; i<5; i++){
a = {};
a['name' + i] = i;
data.push(a);
}
console.log(data);
})()
Like this:
for(i=0; i<5; i++){
var obj = {};
obj["name" + i] = i;
data.push(obj);
}
But I would wonder why you'd want to hard-code the index into the property name.
Since you have an Array, you already have an associated index. It also makes the property hard to look up.
If you need an association of the original index, I'd use a separate property.
for(i=0; i<5; i++){
data.push({name: i, idx: i});
}