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

169
Vistas
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 Respuestas
Responde la pregunta

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 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