Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push a key/ value into JSON objects

Tags:

angularjs

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));
});
like image 550
texas697 Avatar asked Dec 02 '14 21:12

texas697


People also ask

Can a value be the key in JSON?

Keys must be strings, and values must be a valid JSON data type: string. number.

What is toJSON () in JSON?

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.


2 Answers

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;
});
like image 130
KhalilRavanna Avatar answered Oct 17 '22 04:10

KhalilRavanna


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;
});
like image 21
Nate-Bit Int Avatar answered Oct 17 '22 05:10

Nate-Bit Int