Example of Deep Cloning Method for JS Objects

  • 2021-08-05 08:04:40
  • OfStack

In this paper, an example is given to describe the deep cloning method of JS objects. Share it for your reference, as follows:

The objects created in js point to memory, so in the development process, the attributes of one object are often modified, which will affect the other one.

Especially in the framework of angular, dom is driven by data. In the operation of adding, deleting, modifying and checking objects, the inheritance relationship of object attributes is very headache!

The problem I encountered before is that in the editing page, I operated the object data, which affected the presentation of the presentation data!

I have sorted out two methods of deep cloning objects for your reference!

First var 1 false data

var schedule = {"status":21,"msg":"ok","data":[{"name":"lemon","age":21,"contactList":{"phone":[152,153,154],"email":5295}},{"name":"lara","age":22,"contact":{"phone":152,"email":5295}}]}

Method 1:

Traverse itself, judge whether the current object is obj or list, and clone a new object


function deepClone(obj)
{
  var o,i,j,k;
  if(typeof(obj)!="object" || obj===null)return obj;
  if(obj instanceof(Array))
  {
    o=[];
    i=0;j=obj.length;
    for(;i<j;i++)
    {
      if(typeof(obj[i])=="object" && obj[i]!=null)
      {
        o[i]=arguments.callee(obj[i]);
      }
      else
      {
        o[i]=obj[i];
      }
    }
  }
  else
  {
    o={};
    for(i in obj)
    {
      if(typeof(obj[i])=="object" && obj[i]!=null)
      {
        o[i]=arguments.callee(obj[i]);
      }
      else
      {
        o[i]=obj[i];
      }
    }
  }
  return o;
}
var scheduleClone = deepClone(schedule)
scheduleClone.data[0].contactList.phone[0] = 99999999999
console.log(' Method 1  Deep cloning ')
console.log(scheduleClone)
console.log(JSON.stringify(schedule))
console.log(JSON.stringify(scheduleClone))

Method 2:

Using js native json serialization, simple and rude!


var scheduleClone2 = JSON.parse(JSON.stringify(schedule));
console.log(' Method 2  Deep cloning ')
console.log(scheduleClone2)
scheduleClone2.data[0].contactList.phone[0] = 8888888
console.log(JSON.stringify(schedule))
console.log(JSON.stringify(scheduleClone2))

More readers interested in JavaScript can see the topics of this site: "javascript Object-Oriented Introduction Tutorial", "JavaScript Error and Debugging Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "JavaScript Traversal Algorithm and Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: