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

At first, I'm not talking about deep cloning of one object to another.

I have one object:

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

value1 and value2 can be any data types, such as an object or an array.

I have another object:

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

value3 and value4 can be any data types, such as an object or an array.

Now I want to clone all the properties of data2 into data1.

The reason I want this is a link to data1, after changing the properties of data1 I don’t want to break the link.

If I'm something like

 data1 = clone(data2)

I will break the link.

Update: Which means breaking links:

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

If I do this:

data1 = clone(data2);  

Now we still point to the old data1, its value is still:

{
   p1: value1
}

But I want ref to be data2

+4
source share
3 answers

:

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

, , . " ", .

, , ...

IE10 , __proto__ setPrototypeof, dest src:

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

Try:

Object.extend(data1, data2);

+1

Using jQuery.extend()

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

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

-1
source

All Articles