Home > Software design >  How to copy js object that contains function
How to copy js object that contains function

Time:01-07

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:

  1. I have a form-control that allows me to change obj1, obj2 or obj3 value key.
  2. This "new" value that is being assigned to the nested object, is needed for the function.
  3. 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.

  •  Tags:  
  • Related