Naveen Naveen - 5 months ago 20
Javascript Question

Copy associative array in javascript?

I've the following piece of code for copying one associative array to other,

<script>

var some_db = new Array();

some_db["One"] = "1";

some_db["Two"] = "2";

some_db["Three"] = "3";

var copy_db = new Array();

alert(some_db["One"]);

copy_db = some_db.slice();

alert(copy_db["One"]);


</script>


But the second alert says "undefined".. Am I doing something wrong here? Any pointers please..

Answer

In JavaScript associative arrays are called objects.

<script>

var some_db = {        
   "One" : "1",    
   "Two" : "2",    
   "Three" : "3"    
};

var copy_db = clone(some_db);

alert(some_db["One"]);

alert(copy_db["One"]);    

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
}

</script>

I would normally use var copy_db = $.extend({}, some_db); if I was using jQuery.

Fiddle Proof: http://jsfiddle.net/RNF5T/

Thanks @maja.

Comments