Array.push() makes all elements the same when pushing an object
The problem is not with the push
method of the Array.prototype
but with your bindings.
You are modifying the same s
object in every iteration in your async.foreach
block which is actually the same Object as the previously defined Subscriber
.
First you should move the declaration of the s
variable to the foreach block.
And also if you want to create an object with default values, it should be a function
, which returns a new object:
function Subscriber() {
return {
'userID': '',
'email': '',
'name': '',
'stage': '',
'poster': false,
'canEmail': false,
'stage': ''
};
};
And then you can instantiate a Subscriber
object like this:
var s = Subscriber();
See this answer or Closures on MDN for more explanation.
When pushing objects to array, how to not push same object?
As you are using React, you should be able to safely use the ES6 Set Object, which lets you store unique values of any type. (https://devdocs.io/javascript/global_objects/set).
e.g.
handleSubmit(){
let students = []
for(let idx in this.state.checked){
if(this.state.checked[idx] ){
students.push(this.state.allStudent[idx])
}
}
students = [...new Set(students)];
console.log('students', students)
this.setState({
studentList: update(this.state.studentList, {$push: students})
})
}
Array of objects contains same object over and over again
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);
Pushing object to array results in same value
This is because you are adding the same variable every iteration of the loop.
Try changing your push like this:
SubAssessmentScores.push({
Parent: P,
Value: V
});
That said, I recommend you study a little more javascript and conventions in the language, for example your variable naming is frowned upon because you should only use capital letters on the beginning of a name for constructor functions.
A good book is Javascript the good parts by Douglas Crockford.
Javascript pushing objects into array changes entire array
When you push servermessage
into servermessagelist
you're really (more or less) pushing a reference to that object. So any changes made to servermessage
are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.
Declare a function as follows:
function cloneMessage(servermessage) {
var clone ={};
for( var key in servermessage ){
if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
clone[key]=servermessage[key];
}
return clone;
}
Then everytime you want to push a message into the list do:
servermessagelist.push( cloneMessage(servermessage) );
Pushing to one element in a nested array is adding to all elements in javascript
let arr = new Array(4).fill([])
This is creating arr
as an array of four references to the same array ([]
passed as argument). Thus, modifying any of the references modifies the underlying array, and since it's referenced by all of them, you will notice this when logging the object.
> arr[0] === arr[1]
< true
Just use a good ol' for
, or even simply [[],[],[],[]]
if we are just talking about 4 elements.
let arr = new Array(4)
for (let i = 0; i < arr.length; i++)
arr[i] = new Array()
> arr[0] === arr[1]
< false
Array.push is correctly pushing iterated objects to an array, but once the array is returned by method, all object properties have become the same
What is happening in your code:
You have an object coord
. You are pushing its reference to the array, in each iteration. All your array elements point to coord
. You are changing the properties of the object coord
again in turn changing your array elements.
let coord = {x: startPos.x, y: startPos.y}
for (let i = 0; i < this.text.length; i++) {
result.push ({x : coord.x , y : coord.y})
coord.x = coord.x + printDir.x
coord.y = coord.y + printDir.y
}
return result
I am now sending a new object in each loop.
array has got same item every push
You have one object temp_item
that you create before your loop. Then, your loop just sets properties on that one object and then pushes the object into the array. Since pushing into an array does NOT create a copy of the object, you end up just modifying the same object over and over in the loop and pushing the same object over and over into the array.
So, you get an array of all the same object that have the properties as set by the last iteration of your loop.
You can fix it by creating a new temp_item
object after you push the previous one into the array, thus you end up with a new object in the array each time you do meta.push(temp_item)
.
let meta = [];
let counter = 0;
let temp_item = {};
for (let ele of found_spec) {
let ele_clean = cleanItem(ele)
if (ele.includes(':<')) {
temp_item.label = ele_clean;
} else {
temp_item.value = ele_clean;
}
counter++;
if ((counter % 2) == 0) {
meta.push(temp_item);
// now create a new temp_item object for future iterations
temp_item = {};
}
}
Pushing objects in an array only returns last object pushed
it will give all array values
function obj(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
var array = new Array();
var point = new obj("ga", "gadget", "$6.99");
array.push(point);
var point = new obj("ga2", "gadget2", "$7.9");
array.push(point);
Related Topics
Check If Option Is Selected with Jquery, If Not Select a Default
How to Give Keyboard Focus to a Div and Attach Keyboard Event Handlers to It
Positive Look Behind in JavaScript Regular Expression
Onclick Event Getting Called Automatically
How to Implement Custom Sort to a Specific Column After Jqgrid Has Been Generated
JavaScript Decoding HTML Entities
Using Ajax to Read Local Files
Uncaught Typeerror: Cannot Read Property 'Value' of Null
How to Consume Http Component Efficiently in a Service in Angular 2 Beta
Is There a Difference Between (Function() {...}()); and (Function() {...})();
How to Get the Difference of Two Dates in Mm-Dd-Hh Format in JavaScript
Throwing Strings Instead of Errors