I have issues with copying my object that has a function in itself. see below code and afterwards explanation of issue.
const obj1 = {...object1};
const obj2 = {...object2};
const obj3 = {...object3};
const parentObj = {
id: "123",
name: "foo",
nestedObj: [obj1, obj2, obj3],
somefunc(){
return obj1.value obj2.value obj3.value
}
}
My way of copying this object...
const copyObj = {
...parentObj,
nestedObj: parentObj.nestedObj.map(obj=>{
return{
...obj
}
})
}
The issue with above is the following:
- I have a form-control that allows me to change obj1, obj2 or obj3 value key.
- This "new" value that is being assigned to the nested object, is needed for the function.
- However when being copied, my function is always using the original value of the nestedObj.
Is there a way for me to bind the function the the newly copied parentObj?
CodePudding user response:
If somefunc is called like copyObj.somefunc() such that the this value corresponds to the object you call the method on, then it will work when you define somefunc as follows:
somefunc(){
return this.nestedObj.reduce((sum, obj) => sum obj.value, 0);
}
So if now nestedObj has the objects you really want to use, then somefunc will produce the expected sum, provided it is called on the right container object.
