Home > Net >  Modify only the object of the clone
Modify only the object of the clone

Time:01-31

I have an array of profiles, and I want to edit one of them to set the value of a property, so I created a clone using cloneDeep:

 let newProfiles = []
 let newProfile = cloneDeep(this.profiles.find(p => p.id === data.profileId));
 newProfile.hasUser = true;
 newProfiles.push(newProfile);

So this is creating clone of the global object filtering a profile by Id, so this works well, now I want only to modify the object I modified in the original list if I use it like this:

this.profiles = newProfiles;

It removes all the profiles and just takes the new one; how can I keep with the full list and only modify the new profile I modified?

CodePudding user response:

If you replace the old version of the user's profile anyway, why not edit the profile in place?

this.profiles.find(p => p.id === data.profileId).hasUser = true;

I don't know why you would use clonedeep here, but if you want your code to work the way you started to solve this, you would need to remove the profile you've updated first and then push the updated version into the array.

CodePudding user response:

In order to solve this I removed the profile first then reassign to list as:

let newProfiles = cloneDeep(this.profiles);
     let profileEdited = newProfiles.find(p => p.id === data.profileId)

     //delete profile from copy
     var currentProfile = newProfiles.indexOf(profileEdited);
     newProfiles.splice(currentProfile, 1);

     //re-asign profile
     profileEdited.hasUser = true;
     newProfiles.push(profileEdited);

     this.profiles = newProfiles;
  • Related