Probably this is an obvius question, but I'm pretty new on JS. This is always inserting the same item repeated, it is changing the value of the last item inserted on the array when the object change the value, how can I avoid it and insert all the values that I¡m itereating?
self.user.userSociedadesAreasLink =[];
var userSociedadesAreasLink = {};
for(var i =0 ; i< self.selectedSociedades.length ; i++){
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
2 Answers 2
You are using the same object every time to push into the array, only changing the property's value. You have to create a new object everytime to make it as a unique object.
self.user.userSociedadesAreasLink =[];
for(var i =0 ; i< self.selectedSociedades.length ; i++){
var userSociedadesAreasLink = {};
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
This should solve the issue.
2 Comments
You could just push a new object literal each time. You could also just use a map operation for this.
self.user.userSociedadesAreasLink = self.selectedSociedades.map(s => ({sociedad: s}));