4

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'

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
gman
  • 167
  • 1
  • 16

1 Answers1

3

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

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Object.assign doesn't work for ie(11) so I had to add a polyfill function. (http://stackoverflow.com/questions/35215360/getting-error-object-doesnt-support-property-or-method-assign) – gman Mar 27 '17 at 16:53