Creating associative arrays in JavaScript

Using the following code:

$credits.getCredits = function() { return $(this).find( 'tbody' ).children( 'tr' ).map(function(){ var $name = $(this).children(':first').html(); var $role = $(this).children(':nth-child(2)').html(); return { $role: $name }; }).get(); } 

which scans the items in the credit list and should return a listing, as shown below:

 [ { 'Make-up': 'Bob' }, { 'Make-up': 'Susan' }, { 'Photography': 'Charlie' }, { 'Lighting': 'Mike' }, { 'Props': 'One-handed Tony' } ] 

As a result, he outputs this:

 [ { '$role': 'Bob' }, { '$role': 'Susan' }, { '$role': 'Charlie' }, { '$role': 'Mike' }, { '$role': 'One-handed Tony' } ] 

How do you fix the creation of an associative array to get the desired result?

+4
source share
3 answers

You need to return it a little differently if you want a dynamic name, for example:

 $credits.getCredits = function() { return $(this).find( 'tbody' ).children( 'tr' ).map(function(){ var $name = $(this).children(':first').html(), $role = $(this).children(':nth-child(2)').html(), result = {}; result[$role] = $name; return result; }).get(); } 

Here you can try an example (check the console). This is, well, just like the literal syntax of an object works. Since they are equivalent:

 object.propertyName object["propertyName"] 

You can assign via the same route.

+10
source

Create an object (associative array) in two stages:

 var obj = {}; obj[$role] = $name; return obj 

Whenever you use literals to create an object ( {foo: bar} ), the key will also be taken literally and not evaluated.

+13
source

There are no associative arrays in JS. Just create a new object and assign it as you want, for example:

 var $obj = {}; $obj.MakeUp = 'Bob'; 
+2
source

Source: https://habr.com/ru/post/1316075/


All Articles