4

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

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
diwatu
  • 5,641
  • 5
  • 38
  • 61

3 Answers3

4

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);
}
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
1

Try:

Object.extend(data1, data2);

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Doug Leary
  • 199
  • 8
-2

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

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
  • 1
    This will copy properties from both objects to a new one. 1. it will break the reference, 2. it will not clear original properties. – Slava Fomin II May 04 '17 at 10:27