Reputation: 167
I have an array of Drug Codes 'BARB', 'HALU', 'METH'
. I want to loop thru these codes and create a new object for each one.
var saveObj = {};
saveObj.SelectedList = [];
angular.forEach(self.DrugNamesSelected, function(value, key) {
//Load Objects into array
var newObj = {};
newObj = self.Selected;
newObj.FK_CLNT_PERSFK_PER = $routeParams.personId;
newObj.DRUG_TYP_CODE = value;
saveObj.SelectedList.push(newObj);
});
This is what I'm getting
saveObj.SelectedList[0].DRUG_TYP_CODE = 'METH' saveObj.SelectedList[1].DRUG_TYP_CODE = 'METH' saveObj.SelectedList[2].DRUG_TYP_CODE = 'METH'
This is what I need
saveObj.SelectedList[0].DRUG_TYP_CODE = 'BARB' saveObj.SelectedList[1].DRUG_TYP_CODE = 'HALU' saveObj.SelectedList[2].DRUG_TYP_CODE = 'METH'
Upvotes: 4
Views: 255
Reputation: 136154
Seems like newObj = self.Selected;
making you a problem. So what happening is each element is storing a reference of self.Selected
(i.e. all objects are referring to single memory reference). So as last value updates to METH
, all 3 elements has same self.Selected
value.
angular.forEach(self.DrugNamesSelected, function(value, key) {
//Load Objects into array
var newObj = {};
//newObj = self.Selected; //removed this line
newObj.FK_CLNT_PERSFK_PER = $routeParams.personId;
newObj.DRUG_TYP_CODE = value;
saveObj.SelectedList.push(newObj);
});
If you need that particular object assignment for some reason, I'd suggest you to use Object.assign
which will copy self.Selected
properties to newObj
.
Object.assign(newObj, self.Selected)
IE11 doesn't support Object.assign
out of the box. You could consider adding polyfill for the same from here
Upvotes: 3