Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda