ddinchev
ddinchev

Reputation: 34673

CoffeeScript: one liner to map object into another

I have data in the following format:

data = {
  car1: {
    starting_position: 1,
    ...  
  },
  car5: {
    starting_position: 2,
    ...
  }
}

I want to create an object where starting_position becomes the key and the key in the original data becomes the value. I can do it like this:

byStartingPosition = {}
for k, properties of data
  byStartingPosition[properties.starting_position] = k

But I can't imagine there is no one liner to do the same...

Upvotes: 1

Views: 45

Answers (3)

Kamil Szot
Kamil Szot

Reputation: 17817

If you are using lodash 4.1.0 or later you could do it with this function https://lodash.com/docs#invertBy

_.invertBy data, (v) -> v.starting_position

https://jsfiddle.net/7kf9wn71/2/

Upvotes: 1

Jared Smith
Jared Smith

Reputation: 21965

Rayon's comment was aaalmost there. You want to use reduce:

byStartPos = Object.keys(data).reduce(((obj, k) -> start = data[k].starting_position; obj[start] = k; obj), {})

Although that's obnoxiously long, not very idiomatic coffeescript, and frankly less readable than your original, it is a one-liner.

Upvotes: 0

kba
kba

Reputation: 1177

You cannot reduce it semantically but you can make it more concise

byStartingPosition = {}
byStartingPosition[v.starting_position] = k for k,v of data

Upvotes: 1

Related Questions