隆Caminando hacia el 茅xito!

Aprende en Comunidad

Avalados por :

C贸mo clonar un objeto en JavaScript: Soluciones y comparativa de rendimiento

  • Creado 01/03/2024
  • Modificado 01/03/2024
  • 3 Vistas
0
Cargando...
One fine day, Everything was moving smoothly, until a basic assignment operation failed. 馃槓

I'm here trying to clone an object to another.
    
      a = { "val": 10 }
      {val: 10}
      b = a
      {val: 10}
      b.val = 30
      30
      a -> {val: 30}
    
  

A basic operation where assigning value made me debug everything for hours.

both the variables reference the same object. Thus change in one is reflected to the other.

Later I found, As the value of a which was assigned to b. Any change in b is reflected to a at the same time.

How to solve this??

There can be multiple ways. I'm here listing three ordered by their performance.

1. Query.extend

using : jQuery.extend( [deep ], target, object1 [, objectN ])


or

jQuery.extend( target [, object1 ] [, objectN ])


In case of complex objects, deep = true decreases the performance.
    
      var a = { "a": 10 };
      var b = {};
      jQuery.extend(true, b, a);
    
  


2. Object.assign.
    
      var a = { "a": 10 };
      var b = {};
      Object.assign(b, a);
    
  

3. JSON.parse(JSON.stringify());

    
      var a = { "a": 10 };
      var b = {};
      b = JSON.parse(JSON.stringify(a));
    
  

Comparing the performance :





this is not a big issue but for people who are new with JavaScript, this can be a pain.

Pedro Pascal
Se uni贸 el 07/03/2018
Pinterest
Telegram
Linkedin
Whatsapp

Sin respuestas

No hay respuestas para mostrar No hay respuestas para mostrar Se el primero en responder

contacto@primeinstitute.com

(+51) 1641 9379
(+57) 1489 6964

漏 2024 Copyright. Todos los derechos reservados.

Desarrollado por Prime Institute

隆Hola! Soy Diana, asesora acad茅mica de Prime Institute, ind铆came en que curso estas interesado, saludos!
Hola 驴Puedo ayudarte?