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'

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Object.assign doesn't work for ie(11) so I had to add a polyfill function. (stackoverflow.com/questions/35215360/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.