Five. JavaScript implements the object merging function

Source: Internet
Author: User
Tags shallow copy

$.extend () in JQuery is often used to tool functions, many for merging parameters (objects) extend (bool,{},item1,item2 ...).

A bool parameter of TRUE indicates a deep copy, and a shallow copy when False. {} indicates that the merge result is put in it, which can be explained by an example:

Example:

var item={name: "Olive", Age:23,address{provice: "Henan", City: "Zhengzhou"};

var item1={sex: "Girl", Address{city: "Beijing"};

var result=$.extend (TRUE,ITEM,ITEM1);

var result1=$.extend (FALSE,ITEM,ITEM1);

Results:

Result={name: "Olive", Age:23,sex: "Gril", Address:{provice: "Henan", City: "Beijing"};

Result1={name: "Olive", Age:23,sex: "Gril", address:{City: "Beijing"};

Description

The above results show that when the parameter is ture, which is a deep copy, when the subkey in subkey Item1 has the same value as the subkey in item, the value of the ITEM1 sub-item overrides the value in the Item subkey, and when the child item Item1 property is not the same as the property in item. will be merged with item.

When the argument is false, the subkey in the subkey Item1 is in the same time as the subkey property in item, and the value of the ITEM1 item is completely overwritten by the value in item.

This article refers to the source code of jquery's Extend method, merges its own objects, and copies the properties of multiple objects to the target object, and if there is the same property, the object behind it overwrites the previous one.

The method of shallow copy to realize object merging
functionExtend () {//extend shallow copy implementation      varname,options,copy, Length=Arguments.length, I= 1, Target= Arguments[0] | | {};//take target object          if([' object ', ' function '].indexof (typeofTarget) < 0) {target= {}; }           for(; i<length;i++) {Options=Arguments[i]if(Options! =NULL){//conditions for excluding null parameters extend ({},,)           for(NameinchOptions) {//iterating over an object assignmentCopy=Options[name]; if(Copy!==undefined) {Target[name]=copy; }          }        }      }      returnTarget}//test Data    varTest1 ={A:1, B: {c:2, D:3}, E: [1, ' a ']}, Test2={b: {c:4, D:5, F:6}, E: [1, ' a '], G:7    }    varTest =extend ({},test1,test2);   Console.log (TEST.B.D); //5TEST2.B.D= ' x ';//Modify Test2Console.log (TEST.B.D);//the ' x ' Test is modified with

Ideas are as follows:

1, the default to take the first parameter is the target object, if the first parameter is non-object data type, the assignment is an empty object

2. Iterate through the remaining parameters (source object) and copy the properties of the source object onto the target object.

3. Return the target object as the result of the merge

In the second step, the source object's property values are not judged, all use ' = ' assignment, so when the source object's property value is the object property, the copy is only the reference value, that is, a shallow copy, in the test results can be seen in testing and Test2 B property value, using the same object, will affect each other. With that in mind, there should be a way of thinking about how to implement a deep copy of the merge.

Deep copy method for object merging

You need to determine the type of the value when copying the Source object property value, or, if it is an object data type, call the Extend function recursively. You can practice deep copy of the object merging, the implementation of the following:

functionExtend () {//extend deep Copy implementation      varname,options,src,copy, deep=false,//whether deep copy defaults to FalseLength =Arguments.length, I= 1, Target= Arguments[0] | | {}; //If the first argument is a Boolean type, the value is assigned to the deep      if(typeoftarget = = ' Boolean ') { deep= Arguments[0]; Target= Arguments[i] | | {};//target Object Deferredi++; }      //If Target is not an object data type, target assigns a value of {}      if([' object ', ' function '].indexof (typeofTarget) < 0) {target= {}; }       for(; i<length;i++) {Options=Arguments[i]; if(Options! =NULL){           for(Nameinchoptions) {Copy=Options[name]; SRC=Target[name]; if(target = = copy) {//Avoid repeating loops              Continue; }            if(Deep && Copy && (typeofcopy = = ' object ') {//Type judgmentsrc= Object.prototype.toString.call (copy) = = ' [Object Array] '? [] : {};//distinguish between arrays and ' objects 'Target[name] =extend (deep,src,copy); }Else {              if(Copy!==undefined) {Target[name]=copy; }            }          }        }      }      returnTarget}

1, parameter judgment, if the first parameter is a Boolean type, then take as the control depth copy of the parameter deep, the default is False, and the target element is the second parameter

2. When copying attribute values, determine the type of the deep parameter and the attribute value; If Deep is true and the property value is object type, the Extend function is called recursively, otherwise the direct assignment

3. You need to distinguish between arrays and ' objects ' to assign different initial values to the properties of the target object. If all is {}, the property value of the array type will be copied to the target element {' 0 ': xx, ' 1 ': xx ...}

Five. JavaScript implements the object merging function

Related Article

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.