Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  148] [ 6]  / answers: 1 / hits: 45901  / 13 Years ago, thu, july 28, 2011, 12:00:00

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?



edit:



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.


More From » javascript

 Answers
13

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



var myHash = new Object();


or



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.to = myHash.from;
delete myHash.from;

[#90940] Wednesday, July 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tammyb

Total Points: 278
Total Questions: 101
Total Answers: 103

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
;