angelokh
angelokh

Reputation: 9428

Convert all keys in a nested map to camel case in Scala

I have a map like this:

Map("first_key"->"first_value",
    "second_key"->Map("second_first_key"->"second_first_value"))

How can I recursively convert all keys to like this in scala:

Map("firstKey"->"first_value",
    "secondKey"->Map("secondFirstKey"->"second_first_value"))

Upvotes: 6

Views: 4784

Answers (1)

dhg
dhg

Reputation: 52681

This should do what you want:

def convert(m: Map[String, Any]): Map[String, Any] = {
  m.map {
    case (k, v) =>
      val k2 = toCamel(k)
      val v2: Any = v match {
        case s: String => s
        case x: Map[String, Any] => convert(x)
      }
      k2 -> v2
  }
}

def toCamel(s: String): String = {
  val split = s.split("_")
  val tail = split.tail.map { x => x.head.toUpper + x.tail }
  split.head + tail.mkString
}

val m = Map("first_key"->"first_value",
            "second_key"->Map("second_first_key"->"second_first_value"))

convert(m)
// Map(firstKey -> first_value, secondKey -> Map(secondFirstKey -> second_first_value))

Upvotes: 5

Related Questions