4

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?

0

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your solution does work, however Nick Craver also tidied up the code somewhat - so will have to award him the answer.
@Metalshark: Of course, whatever helped you most! :) (@Nick is just awesome regarding JavaScript ;))
10

You need to return it a little differently if you want a dynamic name, like this:

$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();
}

You can try an example here (check the console). This is, well, just the way object literal syntax works. Since these are equivalent:

object.propertyName
object["propertyName"]

You can assign via that same route.

Comments

2

There are no associative arrays in JS. Just create a new object and assign like you want, e.g:

var $obj = {};
$obj.MakeUp = 'Bob';

2 Comments

How does this help the OP using dynamic keys?
right it needs the [] operator, but the idea is the same: first create the object and then add it later, sorry for double post but the posts are all just secounds away from each other

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.