Angular2: Deep copy or angular.copy replacement in Angular2

Standard

As you are aware of fact Angular 1.x had angular.copy in order to deep copy arrays and objects. We need this so that I can copy the object and lose its reference, which means I create a new object with clean reference history (_proto is not polluted) . Otherwise simple assignment will be a shallow copy and any change in source object will be visible in target object.

Please see my previous post from stone-age 😀 :

PREVENT CHANGES IN PARENT SCOPE UNTIL SAVE OPERATION IS PERFORMED IN MODAL

Solution:

Assume you are using ES5/ECMAScript 2015 then Use Object.assign() , this method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Syntax

Object.assign(target, ...sources)

Example

let course = {
  name: 'Database',
  id: 7
};

let newCourse= Object.assign({}, course);

newCourse.name= 'Dataware';

console.log(course.name); // writes Database
console.log(newCourse.name); // writes Dataware

Use polyfill for older browser.

For Nested Objects

You may take help of 3rd party libraries, for deep copying objects:

  • In case of jQuery: use $.extend() function
    var arr =[['abc'],['xyz']];
    var newArr = $.extend(true, [], arr);
    newArr.shift().shift();
    
    console.log(arr); //arr still has [['abc'],['xyz']]
  • In case of lodash, use _.cloneDeep() or _.cloneDeepWith
    let course = [{ name: 'Database', id: 7 },
                  { name: 'OS, id: 6}];
    
    let newCourse= _.cloneDeep(course);
    
    console.log(course[0] === newCourse[0]); // False
    

    Include lodash in Angular 2 application

  • In case of underscore, use _.clone() or underscore.deepclone
Advertisements

4 thoughts on “Angular2: Deep copy or angular.copy replacement in Angular2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s