diwatu
diwatu

Reputation: 5699

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

Upvotes: 4

Views: 3877

Answers (3)

Doug Leary
Doug Leary

Reputation: 318

Try:

Object.extend(data1, data2);

Upvotes: 1

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

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);
}

Upvotes: 4

Lumi Lu
Lumi Lu

Reputation: 3305

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

Upvotes: -2

Related Questions