Reputation: 15
I need send the objects to api. But I need to change one value of the object in every step of the loop.
this.task = {
RowId: 0
};
var taskWithFid = [];
var fids = [1,2,3,4,5];
var taskTemp = this.task;
fids.map(function(fid){
taskTemp.RowId = fid;
taskWithFid.push(taskTemp);
}.bind(this));
I expect taskWithFid
array like this:
[
{ RowId: 1 },
{ RowId: 2 },
{ RowId: 3 },
{ RowId: 4 },
{ RowId: 5 }
]
But I get this:
[
{ RowId: 5 },
{ RowId: 5 },
{ RowId: 5 },
{ RowId: 5 },
{ RowId: 5 }
]
Can you help me with that?
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js" data-require="[email protected]"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl as item">
<h1>Hello Plunker!</h1
<div>{{item.taskWithFid}}</div>
</body>
</html>
Upvotes: 1
Views: 243
Reputation: 2117
Here is the right reason
In Javascript objects and arrays are pushed by reference. Objects and arrays not are pushed as copy.
In your code when you are doing following lines you are simply pushing object reference to array.
taskTemp.RowId = fid;
taskWithFid.push(taskTemp);
At the end the last value is changing all values because of this reference.
Solution
We just need to create a separate object every time we push. Most of the answers are correct here. But still following is my solution:
fids.map(function(fid){
this.taskWithFid.push({RowId: fid});
console.log('fid: '+fid);
}.bind(this));
Upvotes: 0
Reputation: 2043
Your this.task
is override each time when you change RowId
move your task
inside .map
with new variable as var task { // code }
, so its create new variable each time.
Here is working flunker
fid.map() should be like :
fids.map(function(fid){
var task = {
DateCreated: now.toJSON(),
RowId: 0,
Subject: null
};
task.RowId = fid
this.taskWithFid.push(task);
console.log('fid: '+fid);
}.bind(this));
Upvotes: 0
Reputation: 473
var taskWithFid = [];
var fids = [1,2,3,4,5];
var taskTemp
fids.map(function(fid){
this.task = {
RowId: 0
};
taskTemp =this.task;
taskTemp.RowId = fid;
taskWithFid.push(taskTemp);
}.bind(this));
console.log(taskWithFid);
Upvotes: 0
Reputation: 3712
The problem is that you are pushing the same object into an array, and while doing so you are changing it's RowId. So in the end, when you change it to 5, all will be 5. You need to create separate objects:
fids.map (function(fid) {
taskWithFid.push({RowId: fid});
}.bind(this));
Upvotes: 1
Reputation: 14590
It should be:
this.task = {
RowId: 0
};
var taskWithFid = [];
var fids = [1,2,3,4,5];
fids.map(function(fid){
var taskTemp = {};
taskTemp.RowId = fid;
taskWithFid.push(taskTemp);
}.bind(this));
Move and change var taskTemp = this.task;
to var taskTemp = {};
Upvotes: 0