Copy An Associative Array In JavaScript


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.



As @Niko says in the comment, there aren't any associative arrays in JavaScript.


You are actually setting properties on the array object, which is not a very good idea. You would be better off using an actual object.


var some_db = {};
some_db["One"] = "1";
some_db["Two"] = "2";
some_db["Three"] = "3";

var copy_db = {}, prop;
// Loop over all the keys in the object
for (prop in some_db) {
// Make sure the object has this value, and not its prototype
if (some_db.hasOwnProperty(prop)) {
copy_db[prop] = some_db[prop];
}
}

Many libraries implement an extend function which does exactly this (copy keys from one object to another). Most notably jQuery and Underscore.js. Underscore.js also has _.clone(obj) which is effectively _.extend( {}, obj )



If you want to use JSON, you can take this 'associative array' object:


var assArray = {zero:0, one:1, two:2, three:3, what:'ever', you:'want'};

And 'clone' it like this:


var clonedObj = JSON.parse(JSON.stringify(assArray));


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable