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

172
Visualizações
Create Function to Copy Properties From One Object to Another

I am trying to create a function that will copy all properties from a source object and paste them to a destination object. I want to create a deep copy, so I am not using object.assign().

Here is my code:

var obj1 = {
  arr: ['a','b','c','d'], // >= 4 elements, all should be truthy
  obj: {a:1,b:2,c:3,d:4}, // >= 4 values, all should be truthy
  halfTruthyArr: [null,'b',null,'d'], // >= 4 elements, half should be falsy
  halfTruthyObj: {a:1,b:null,c:3,d:null}, // >= 4 values, half should be falsy
  string: 'This is a string.',
  reverseString: function (string) {
    if (typeof string === 'string') return string.split('').reverse().join('');
  }
};

var obj2 = {}

function extend(destination, source) {
  destination = JSON.parse(JSON.stringify(source))
}

extend(obj2,obj1)

console.log(obj2)
  1. obj2 is not changed using the function. I understand the function uses pass by reference, which is why the object is not reassigned. Is there a way around this so that the object I pass in as a parameter is edited?
  2. The reverseString method in obj1 does not get copied using JSON.stringify. Why is this?
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

if you are setting the value of an object or array inside of function it is Pass by Value. So you need to pass object by reference or try this

function extend(source) {
  return JSON.parse(JSON.stringify(source))
}

var obj2=extend(obj1);

console.log("ext",obj2)

or pass by reference. In this case you are only changing the property inside of the object, not assigning a new value to the whole object


function extend(source, destination) {
  destination.result = JSON.parse(JSON.stringify(source));
}

var destination = { result: {} };

extend(obj1, destination);

var obj2=destination.result;

console.log("ext", obj2);
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