Copy associative array in javascript?

I have the following code snippet to copy one associative array to another,

<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 warning says "undefined". Am I something wrong here? Any pointers please.

+7
source share
4 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 usually use var copy_db = $.extend({}, some_db); if i used jQuery.

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

Thanks @maja.

+17
source

As @Niko notes in a comment, JavaScript has no associative arrays.

In fact, you are setting the properties of an array object, which is not a good idea. You will be better off using the 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 the extend function, which does just that (copies keys from one object to another). Most noticeable are jQuery and underscore.js . The underline also has _.clone( obj ) , which is effectively _.extend( {}, obj )

+4
source

if you want to use JSON, you can take this object "associative array":

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

and 'clone' it looks like this:

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

+2
source

underscore.clone ( http://underscorejs.org/#clone ) can help. It performs a shallow copy of an object or dictionary array.

 var some_db = { "One" : "1", "Two" : "2", "Three" : "3" }; copy_db = _.clone(some_db); 
0
source

All Articles