How to push a key/ value into JSON objects

38,679

Solution 1

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;
});

Solution 2

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;
});
Share:
38,679

Related videos on Youtube

texas697
Author by

texas697

Junior Web Developer

Updated on August 09, 2022

Comments

  • texas697
    texas697 5 months

    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));
    });
    
  • texas697
    texas697 about 8 years
    up vote for being correct but a few minutes behind the first guy! thanks though
  • Silvan
    Silvan almost 7 years
    Thanks, in my case i need it as an array. So you can use this with the brackets: $scope.array.push({[JobId]:Job[JobId]}); Hope this will helps anyone also ...

Related