Javascript – Change key in js associative array


If I have:

var myArray = new Array();myArray['hello'] = value;

How can I change the key 'hello' to something else?

Something like this would work.

var from = 'hello',    to   = 'world',    i, value = myArray[from];for( i in myArray )  if( i == from ) myArray.splice( i, 1 );myArray[to] = value;

But is there a native function or a better way to do it?


Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.

Best Solution

In JavaScript there is no such thing as associative Array. Objects can be used instead:

var myHash = new Object();


var myHash = {};

replace can be done like this:

myHash["from"] = "value";myHash["to"] = myHash["from"];delete myHash["from"];

but the preferred way to write it:

myHash.from = "value"; = myHash.from;delete myHash.from;