Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to copy js object that contains function

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda