Gary Sieling

Lodash: reverse a map

The following code snippet will take a Javascript object, and swap the keys and values. In order to handle duplicates, the result puts values into arrays.

For instance, this object:

let categories = {
  "History": {
    "Political History": {},
    "20th century history": {}
  },
  "Politics": {
    "Political History": {},
    "American Politics": {}
  }
}

Turns into this:

{
  "Political History": ["History", "Politics"],
  "20th century history": ["History"],
  "American Politics": ["Politics"]
}

Code example:

_.mapValues(
  _.groupBy(
    _.flatMap(
      _.keys(categories), 
      k1 => 
        _.map(
          _.keys(categories[k1]), 
          k2 => [k2, k1] 
        ) 
      ), 
  tuple => tuple[0]), 
  (v) => 
    _.flatMap(v, 
      v => _.filter(
             v, 
             (value, idx) => idx % 2 == 1)
    )
)
Exit mobile version