How to push key / value into JSON objects

I am trying to push Id into an array of Json objects. Each object must have a "JobId": the value is "inserted" before sending it to apiController. I am trying to use the forEach loop for this, but I am stuck. Right now, instead of inserting this into every object in the array, it is inserting at the end of the array. I have a plunkr installation. 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)); }); 
+6
source share
2 answers

What you do is $scope.array.forEach over each element through $scope.array.forEach , but then you do not actually change the element that is returned from the newJobItem , but simply push the new element: $scope.array.push({'JobId' : JobId}); .

The correct line inside your forEach should be newJobItem.JobId = JobId; . This way you modify existing entries inside $scope.array , rather than just pushing new objects.

In details:

 $scope.array.forEach(function (newJobItem) { $scope.array.push({'JobId' : JobId}); }); 

becomes:

 $scope.array.forEach(function (newJobItem) { newJobItem.JobId = JobId; }); 
+17
source

You want to manipulate the objects in the array, not the array itself. Try the following:

 $scope.array.forEach(function (newJobItem) { var JobId = 143; newJobItem.JobId = JobId; }); 
+4
source

Source: https://habr.com/ru/post/979013/


All Articles