Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"))
like image 498
angelokh Avatar asked Mar 10 '15 04:03

angelokh


1 Answers

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))
like image 161
dhg Avatar answered Nov 03 '22 02:11

dhg