Search code examples
scalaspray-json

How to create HashMap from a Vector in Scala


I have this Vector:

val imageIds = Vector(
  "XXXX1",
  "XXXX2",
  "XXXX3"
)

And I currently create an Array using the following method:

def makeTheImageDataArray: Vector[JsObject] = {
  imageIds.map(SingleImageData(_, "theURL", "theStatus").asJsObject)
}

with this case class:

case class SingleImageData(ImageId: String, URL: String, Status: String) {
  def imageId: String = ImageId
  def getURL: String = URL
  def status: String = Status

  def asJsObject: JsObject = JsObject(
    "ImageId" -> JsString(imageId),
    "URL" -> JsString(getURL),
    "Status" -> JsString(status)
  )
}

Which produces:

Vector(
  {"ImageId":"XXXX1","URL":"theURL","Status":"theStatus"},
  {"ImageId":"XXXX2","URL":"theURL","Status":"theStatus"},
  {"ImageId":"XXXX3","URL":"theURL","Status":"theStatus"}
)

Instead of producing a Vector, I want to create a HashMap instead, with the ImageId as the key, i.e. :

Map(
  XXX1 -> {"URL":"theURL","Status":"theStatus"},
  XXX2 -> {"URL":"theURL","Status":"theStatus"},
  XXX3 -> {"URL":"theURL","Status":"theStatus"}
)

Can anyone show me how to do this?


Solution

  • Remove "ImageId" -> JsString(imageId) from asJsObject, then

    imageIds.map(id => id -> SingleImageData(id, "theURL", "theStatus").asJsObject).toMap
    

    or if SingleImageData doesn't need to know the id, remove ImageID entirely from SingleImageData, and

    imageIds.map(_ -> SingleImageData("theURL", "theStatus").asJsObject).toMap