Javascript objects (object) Merge

Source: Internet
Author: User
Tags hasownproperty

Merging of objects

Requirements: With Object O1, O2, need to get objects O3

var O1 = {A: ' A '}, O2 = {b: ' B '}; then var O3 = {A: ' A ', B: ' B '}

Method 1: Use the Extend method of jquery

* * Method definition **:jquery.extend ([deep], Target, Object1, [objectn])

> extends an object with one or more other objects, returning the object being extended.

> If target is not specified, the jquery namespace itself is extended. This helps plug-in authors add new methods to jquery. If the first argument is set to True, jquery returns a deep copy, recursively copying any objects found (recursive merge). Otherwise, the copy will share the structure with the original object. Undefined properties will not be copied, but properties inherited from the object's prototype will be copied.

O3 = $.extend (O1, O2)  //merge O1 and O2, return the result to O3. Note: At this point, O1 = = o3! is modified//or O1 = O3 ({}, $.extend, O1)//merge O2 and O1, Returns the result to O3. Note: At this time, O1! = o3! That O1 has not been modified

Method 2: Use Object.assign (); Examples of online search:

var O1 = {a:1};var O2 = {B:2};var O3 = {C:3};var obj = object.assign (O1, O2, O3); Console.log (obj); {a:1, B:2, C:3}console.log (O1);  {a:1, B:2, c:3}, note that the target object itself will also change.

Method 3: Traverse the Assignment method

Code logic:

    1. Each of the corresponding properties in the Loop object N.
    2. Confirm that the attribute exists in object n
    3. Confirm that the property does not exist in object o
var extend=function (o,n) {for   (Var p in N) {        if (N.hasownproperty (p) && (!o.hasownproperty (P)))            O[p ]=N[P];    };    

Similar to the direct assignment increment attribute:

O3=o1; o3[' B ']= ' B ';//O3 ={O1: ' A ', O2: ' B '};

  

-----------------------------------------

Javascript objects (object) Merge

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.