Naveen Naveen - 2 years ago 163
Javascript Question

Copy associative array in javascript?

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


var some_db = new Array();

some_db["One"] = "1";

some_db["Two"] = "2";

some_db["Three"] = "3";

var copy_db = new Array();


copy_db = some_db.slice();



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

Answer Source

In JavaScript associative arrays are called objects.


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

var copy_db = clone(some_db);



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;


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

Fiddle Proof:

Thanks @maja.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download