Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy an 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...

like image 932
Naveen Avatar asked Apr 22 '12 18:04

Naveen


1 Answers

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.

like image 59
iambriansreed Avatar answered Sep 23 '22 16:09

iambriansreed