Skip to content

Instantly share code, notes, and snippets.

@jacoblyles
Last active January 3, 2016 13:19
Show Gist options
  • Save jacoblyles/8468924 to your computer and use it in GitHub Desktop.
Save jacoblyles/8468924 to your computer and use it in GitHub Desktop.
This flattens a scala playframework JsObject. The result will not contain any JsObjects as values
def flattenJsObject(obj: JsObject): JsObject = {
val newObj = obj.fields.map {
case (name, value) =>
value match {
case o: JsObject =>
Some((name, o))
case _ => None
}
}.flatMap(o => o).foldLeft(obj) {
case (prev, next) =>
JsObject(prev.fields.filterNot { case (name, value) => name == next._1 }) ++ next._2
}
if (newObj.fields.exists { case (name, value) => value.isInstanceOf[JsObject] }) {
flattenJsObject(newObj)
} else {
newObj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment