在JavaScript中创建关联数组

Met*_*ark 4 javascript jquery associative-array

使用以下代码:

$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();
}
Run Code Online (Sandbox Code Playgroud)

这看起来通过片尾字幕的元素应该返回类似下面的列表:

[
     { 'Make-up': 'Bob' },
     { 'Make-up': 'Susan' },
     { 'Photography': 'Charlie' },
     { 'Lighting': 'Mike' },
     { 'Props': 'One-handed Tony' }
]
Run Code Online (Sandbox Code Playgroud)

它最终输出这个:

[
     { '$role': 'Bob' },
     { '$role': 'Susan' },
     { '$role': 'Charlie' },
     { '$role': 'Mike' },
     { '$role': 'One-handed Tony' }
]
Run Code Online (Sandbox Code Playgroud)

如何修复关联数组创建以获得所需的输出?

Fel*_*ing 13

分两步创建对象(关联数组):

var obj = {};
obj[$role] = $name;
return obj
Run Code Online (Sandbox Code Playgroud)

每当您使用文字创建一个对象({foo: bar})时,该键也将按字面意思进行,不会被评估.


Nic*_*ver 10

如果你想要一个动态名称,你需要以不同的方式返回它,如下所示:

$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();
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里试试一个例子(检查控制台).这就是对象文字语法的工作方式.因为这些是等价的:

object.propertyName
object["propertyName"]
Run Code Online (Sandbox Code Playgroud)

您可以通过相同的路线分配.