Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change key in js associative array

Tags:

javascript

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.

like image 531
Matt R. Wilson Avatar asked Jul 28 '11 20:07

Matt R. Wilson


People also ask

How do I change an object key?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

How do you update an object in an array?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

How do I remove a key from an array of objects?

To remove a property from all objects in an array:Use the Array. map() method to iterate over the array. Use destructuring assignment to extract the property to be removed.


1 Answers

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;
like image 78
KARASZI István Avatar answered Sep 18 '22 01:09

KARASZI István