0

How can I map this array of objects to a new array of objects where the object's id is the key and its value is the object?

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}} ]

I get a syntax error trying the above Uncaught SyntaxError: Unexpected token .(…)

JSFiddle

user2954587
  • 4,661
  • 6
  • 43
  • 101
  • I think you are looking for [reduce](https://underscorejs.org/#reduce) and not [map](https://underscorejs.org/#map) Start with an empty object and build it key by key as you iterate the array of `players`. If you _really_ want an array back, wrap the final object in an array. But I'm pretty sure that was not your intention. – hughc Feb 04 '20 at 23:28

2 Answers2

1

First of all, in your JS Fiddle you were not including underscore, but this will work:

var mapped = _.map(players, function(player) {
  var playerObj = {};
  playerObj[player.id] = player;
  return playerObj;
})
northsideknight
  • 1,519
  • 1
  • 15
  • 24
1

If you're happy using ES6 functionality then you could use an arrow function which makes use of a computed property name:

var mapped = _.map(players, player => ({ [player.id] : player}));
Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
  • Any reason for the down vote? Anonymous down votes with no comments don't help anyone and I would really like to know where there is a problem so that I can learn from it and correct the answer. – Gruff Bunny Apr 10 '16 at 08:10
  • Not sure either @GruffBunny, I didn't know i needed the `()` around the object, this helper me – Jonesopolis Sep 16 '20 at 03:02