下划线将对象的数组映射到id为键的新对象

时间:2016-04-09 15:23:37

标签: javascript underscore.js

如何将这个对象数组映射到一个新的对象数组,其中对象的id是键,它的值是对象?

var players = [{id: 2, score: 5}, {id: 3, score: 10}]

var mapped = _.map(players, function(x) { return {x.id: x}})

// desired output = [{2: {id: 2, score: 4}, {3: {id: 3, score: 10}} ]

尝试上述Uncaught SyntaxError: Unexpected token .(…)

时出现语法错误

JSFiddle

2 个答案:

答案 0 :(得分:1)

首先,在你的JS小提琴中,你没有包括underscore,但这会有效:

var mapped = _.map(players, function(player) {
  var playerObj = {};
  playerObj[player.id] = player;
  return playerObj;
})

答案 1 :(得分:0)

如果您对使用ES6功能感到满意,那么您可以使用箭头函数,该函数使用计算属性名称:

form(action="/user/create", method="post")
    label(for="name") Name
    input(type="text", id="name", name="name", value="", autofocus)

    label(for="surname") Surname
    input(type="text", id="surname", name="surname", value="")