JS Object Deep Clone

Source: Internet
Author: User
Tags object serialization

First look at an example:

1 var student = {2     name: "Yxz",3     age:254} 5 var newstudent = student; 6 newstudent.sex = "male"; 7 // {name: "Yxz", Age:25,sex: "Male"}

Thus, when passing an object through a simple pass assignment to a new variable, it simply adds an alias to the object. Therefore, the operation of the alias will also affect the original object, so by Newstudent.sex to the object student Add properties can be implemented. However, more often we want the newstudent and student objects to be independent, then we need to generate a copy of the original object, see the following example:

1 varCloneobj =function(obj) {2     varstr, newobj = Obj.constructor = = = Array? [] : {};3     if(typeofObj!== ' object '){4         return; 5} else if (window. JSON) {6 str = json.stringify (obj),//Serialization of object 7 newobj = Json.parse (str);//restore 8} else {9 for ( var i in obj) {newobj[i] = typeof obj[i] = = = ' object '? Cloneobj (Obj[i]): Obj[i];}12}  -     returnnewobj; - }; the //Test - varStudent = { -Name: "Yxz", -Age:25, +Sex: "Male" - }; + //perform a deep clone A varNewstudent =cloneobj (student); at DeleteNewstudent.sex; -Console.log (newstudent);//{name: "Yxz", age:25} -Console.log (student);//{name: "Yxz", Age:25,sex: "Male"}

By executing the results you can see that newstudent has become a cloned copy, and any action on newstudent will no longer affect the student object.

Note: Json.stringify and parse are JSON object serialization and deserialization functions, which are responsible for serializing the object into a string and deserializing the JSON string into an object, because this belongs to the ECMASCRIPT5 specification, so the red part of the program does a compatible processing.

JS Object Deep Clone

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.