1

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

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.

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

2 Comments

I see what you did to fix the problem, but perhaps you can explain it to benefit others?
Yup, thanks, it was obvious :). I'll accept in the moment I can
0

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}));

Comments

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.