Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Totally basic Javascript reference question

The following in a Javascript console:

var a = {'foo': []};
var b = {};

for (var key in a) {
   b[key] = a[key];
}

a['foo'].push(1);

console.log(b);

Yields:

Object foo=[1]

I want to make a copy by value in b of each array for each key in a. Is there an easier way?

like image 271
Wells Avatar asked Oct 23 '09 18:10

Wells


People also ask

What is JavaScript best answer?

JavaScript is a popular web scripting language and is used for client-side and server-side development. The JavaScript code can be inserted into HTML pages that can be understood and executed by web browsers while also supporting object-oriented programming abilities.


2 Answers

You could make a "clone" function that creates a new object, based on the original object constructor, and then clone that original object properties also if they are objects:

function clone(obj){
  if(typeof(obj) != 'object' && obj != null) 
    return obj; // return the value itself if isn't an object
                // or null, since typeof  null == 'object';

    var temp = new obj.constructor();

    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}


var a = {'foo': []};
var b = clone(a);

a['foo'].push(1);

console.log(b); // Object foo=[0]
like image 148
Christian C. Salvadó Avatar answered Oct 06 '22 00:10

Christian C. Salvadó


This is called Deep Copy. You can find examples in:

  • http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/
  • (Deep) copying an array using jQuery
like image 24
Ivan Nevostruev Avatar answered Oct 05 '22 23:10

Ivan Nevostruev