DEV Community

Leonel Elimpe
Leonel Elimpe

Posted on • Originally published at leonelngande.com on

Deep Cloning Objects in Angular, Typescript, Javascript

Some of the techniques for cloning objects in Javascript are either using object destructuring or a combination of JSON.stringify() and JSON.parse().

const objectA = { foo: { bar: 'baz' } }; // initial value of objectA
const cloneOfObjectA = {...objectA}; // objectA destructured to create cloneOfObjectA

const objectB = { foo: { bar: 'baz' } }; // initial value of objectB
const cloneOfObjectB = JSON.parse(JSON.stringify(objectB)); // create a clone of objectB using JSON.parse() and JSON.stringify()

Each of the above methods has limitations if youโ€™re looking to deep clone your object.

Object destructuring with the spread operator (i.e. Object.assign) for objects const a = {...b} only makes shallow copies of those objects, meanwhile using the JSON methods will dump the prototype chain and any methods on the object (more here).

I am currently taking the Angular Architecture and Best Practices course on Pluralsight and @DanWahlin (itโ€™s author) mentions a really cool and lightweight library for achieving just this: clone.

It offers foolproof deep cloning of objects, arrays, numbers, strings, maps, sets, promises, etc. in JavaScript, has 0 dependencies and at the time of writing has over 607M downloads!

To install it, simple run npm install clone, just follow the readme for more usage notes ๐Ÿ™‚.

Hereโ€™s a wrapper service for the library when using with Angular and Typescript:

import {Injectable} from '@angular/core';
import * as clone from 'clone';

@Injectable({providedIn: 'root'})
export class ClonerService {

    deepClone<T>(value): T {
        return clone<T>(value);
    }

}

And a (quite trivial) usage example:

    const objectA = { foo: { bar: 'baz' } }; // initial value of objectA
    constructor(private clonerService: ClonerService) {
        const cloneOfObjectA = this.clonerService.deepClone(this.objectA);
    }

Hopefully this helps in your deep cloning adventures, happy coding!

Top comments (0)