1

I have a List of Map, each containing three key/value pairs:

List(
  Map("id" -> 1, "key" -> 11, "value" -> 111), 
  Map("id" -> 2, "key" -> 22, "value" -> 222), 
  Map("id" -> 3, "key" -> 33, "value" -> 333), 
  Map("id" -> 4, "key" -> 44, "value" -> 444))

I would like to transform this to JSON but before that I need to remove the key and its value from every map and rename the value key to title. How can this be done in Scala in a elegant way?

0

4 Answers 4

6

You can do this:

val m1 = Map("id" -> 1, "key" -> 2, "value" -> 3)
val m2 = m1 - "key"  // Map(id -> 1, value -> 3)
val m3 = m2 + ("title" -> m2("value")) - "value"
// Map(id -> 1, title -> 3)

So, for an entire list:

list.map(m => m + ("title" -> m("value")) - "value" - "key")
Sign up to request clarification or add additional context in comments.

Comments

3

A similar approach to redefining the given list of maps, which fetches values of interest (an omits the rest),

mapsList.map { m => Map( "id" -> m("id"), "title" -> m("value") )}

1 Comment

Thanks, that fitted my needs perfectly
2

Assuming you keys are String:

listOfMap map { m => (m - "key") + ("title" -> m("value")) - "value" }

That's to say for each element of the list (each m: Map), 1 create a copy without entry with key "key" (m - "key"), 2 create a second copy based on first one by appending a new entry with key "title" and value from entry with key "value" from original map m (+ ("title" -> m)), 3 and finally create finally map that will takes place in new list by removing entry for key "value" (finalizing the 'renaming': - "value").

Comments

1

I'd go with this

 val list = ... // your definition

 list map { 
   _ collect {
     case ("value", v) => "title" -> v
     case tpl @ (k, v) if k != "key" => tpl
   }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.