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));
});
Keys must be strings, and values must be a valid JSON data type: string. number.
toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.
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;
});
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With