Search code examples
scalaplay-json

How to delete Seq[String] from JsObject?


private def updateData(
  oldData: Seq[Data], 
  authorised: Boolean, 
  removeItemList: Seq[String]
): Seq[Data] = {
    if (!authorised) {
      oldData.map { data =>
        val props: Option[JsObject] = data.props.map { 
          props => props.as[JsObject] - removeItemList(0) - removeItemList(1) - removeItemList(2) 
        }
        data.copy(props = props)
      }
    } else {
      oldData
    }
  }

Can we improve this code? so it's work with removeItemList length > 3.


Solution

  • The trick is to, for every item in removeItemList, remove it from the JsObject which resulted from the last removal.

    This is the very definition of a fold:

    removeItemList.foldLeft(props.as[JsObject]) { (jso, v) => jso - v }
    
    • we use props.as[JsObject] as the start value
    • for every item in removeItemList, we combine it with the current value with the combining function
    • the combining function removes the item from the current value