简体   繁体   中英

Replace one object's properties with the properties of another?

First I am not saying deep cloning one object to another.

I have one object:

var data1 = {
               p1: values1,
               p2: values2,
               .....
            };

value1 and value2 can be any data type, like object or array.

I have another object:

var data2 = {
               p3: values3,
               p4: values4,
               .....
            };

value3 and value4 can be any data type, like object or array.

Now I want to clone all data2's properties to data1.

The reason I want this is data1 is referenced, after data1's properties are changed I don't want to breake the reference.

If I do something like

 data1 = clone(data2)

I will break the reference.

Update: What means by breaking the references:

var data1 = {
             p1: value1
          }; 
var data2 = {
              p2: vale2
          };
var ref = data1;

If I do:

data1 = clone(data2);  

Now ref still point to the old data1, its value still be:

{
   p1: value1
}

But I want ref be data2

You could use this function:

function replaceProperties(dest, src)  {
    for (var i in dest) 
        delete dest[i];
    for (var i in src) 
        dest[i] = src[i];
}

The code is obvious and seems like it does what you want. It doesn't "break reference" as you say it.

Though it might not do what you want when properties are not enumerable or from prototypes...

If you don't have to support IE10 and before, using __proto__ or setPrototypeof , you can have your dest update when src properties are changed:

function replaceProperties(dest, src)  {
    for (var i in dest) 
        delete dest[i];
    Object.setPrototypeOf(dest, src);
}

Try:

Object.extend(data1, data2);

Using jQuery.extend()

for the deep copy: var object = $.extend({}, object1, object2);

more information http://api.jquery.com/jQuery.extend/#jQuery-extend-target-object1-objectN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM