Sebastian Basner
Sebastian Basner

Reputation: 515

Remove element from List of Maps in Scala

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?

Upvotes: 1

Views: 1022

Answers (4)

tiran
tiran

Reputation: 2431

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
   }
 }

Upvotes: 1

elm
elm

Reputation: 20435

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") )}

Upvotes: 3

cchantep
cchantep

Reputation: 9168

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").

Upvotes: 2

dhg
dhg

Reputation: 52701

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")

Upvotes: 6

Related Questions