Reputation: 6397
I am trying to push a Id into a Json array of objects. Every object must have '"JobId" : Value' inserted before it is sent to the apiController. I am trying to use a forEach loop for this but I am stuck. Right now instead of inserting this in the each object in the array it is inserting at the end of the array. I have a plunkr setup. plunkr
$scope.array = [{
ESOURCELINEID:"5464",
QBRFQLINESUPPLIERPARTNUMBER:"HW12",
QBRFQLINESUPPLIERQUOTEUOM:"ft"
}, {
ESOURCELINEID:"8569",
QBRFQLINESUPPLIERPARTNUMBER:"LT34",
QBRFQLINESUPPLIERQUOTEUOM:"Meter"
}];
var JobId = 143;
$scope.array.forEach(function (newJobItem) {
$scope.array.push({'JobId' : JobId});
});
var index = 0;
$scope.array.forEach(function (newJobItem) {
console.log('newJobItem #' + (index++) + ': ' + JSON.stringify(newJobItem));
});
Upvotes: 8
Views: 39168
Reputation: 165
You want to manipulate the objects in the array, not the array itself. Try this:
$scope.array.forEach(function (newJobItem) {
var JobId = 143;
newJobItem.JobId = JobId;
});
Upvotes: 4
Reputation: 6058
What you're doing is iterating over each item via $scope.array.forEach
but then you're not actually modifying the item that is returned from the callback newJobItem
but just pushing a new item: $scope.array.push({'JobId' : JobId});
.
The correct line inside your forEach should be newJobItem.JobId = JobId;
. That way you're modifying the existing entries inside $scope.array
instead of just pushing new objects.
More explicitly:
$scope.array.forEach(function (newJobItem) {
$scope.array.push({'JobId' : JobId});
});
Becomes:
$scope.array.forEach(function (newJobItem) {
newJobItem.JobId = JobId;
});
Upvotes: 18