Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 looks through the elements of a credits list and should return a listing like the following:

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

It ends up outputting this instead:

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

How do you remedy the associative array creation to get the desired output?

like image 809
Metalshark Avatar asked Nov 28 '22 04:11

Metalshark


1 Answers

Create the object (associative array) in two steps:

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 will not be evaluated.

like image 92
Felix Kling Avatar answered Dec 05 '22 13:12

Felix Kling