1

Hi
I want to copy array of objects in javascript with functions.

I have object like this

var User = function() {
    this.name = '';
    var surname = '';

    function f() {
        //some function here
    }

    this.sayHello = function() {
        console.log( 'Hello ' + this.name + ' ' + surname )
    }
}

var arr = [];
arr.push([ new User(), new User()]);
arr.push([ new User(), new User()]);

As you see, I have object with some private and public properties declared this and war and private and public functions.

Is there any method to copy this array? I user this method

function copy( arr ) {
    var c = [];
    for( var i = 0; i < arr.length; i ++ ) {
        c.push(arr[i].concat([]));
    }
}

In this method, when I changed some property of some object, property changes for copied object too.

var arr2 = copy(arr)
arr[0][0].name = 'name';
console.log(arr2[0][0].name) // prints 'name'

Is there method to copy nested array of objects with functions ? Than you.

Gor
  • 2,808
  • 6
  • 25
  • 46
  • A nice solution that should work for all cases is [here](http://stackoverflow.com/a/122190/3399432). – UtsavShah Dec 20 '15 at 19:56
  • 1
    There isn't one built-in. And, creating it isn't necessarily simple while keeping prototype chains in place. [Most elegant way to clone a JavaScript object](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object) – Jonathan Lonowski Dec 20 '15 at 19:56
  • 1
    @UtsavShah there really isn't a deep-copy solution that will work for *all* cases; it's a non-trivial problem. However that link you provided is probably the best place to start :) – Pointy Dec 20 '15 at 20:01
  • You're right @Pointy – UtsavShah Dec 20 '15 at 20:02
  • thank you all. but I have one more question . Can I copy object with functions ? – Gor Dec 20 '15 at 20:06
  • @Gor well you can't make a copy of a function, but you don't have to - functions are immutable. Thus, your deep-copy operation only needs to worry about object properties that are array or (non-function) object references. References to functions can just be copied. – Pointy Dec 20 '15 at 23:26

0 Answers0