0

I have a variable descriptions that is an Option[JsonArray] (JsonArray results from calling getJsonArray on a JsonObject). descriptions is a list of objects that I'm getting back as a response from a server. Each object has a structure like so:

{age: String,
 number: Long,
 link: String}

I'd like to loop through this JsonArray and edit the link field to a certain value that is returned from a function. I don't even need to edit it in place and can take a new array of objects. In JS, it might be as simple as descriptions.map(d => ({...d, link: someValue})) but I'm not sure how I need to transform the JsonArray to get this working in Scala. Any help is appreciated!

mysl
  • 1,003
  • 2
  • 9
  • 19
  • 2
    Which library are you using? – Luis Miguel Mejía Suárez May 28 '22 at 02:54
  • 2
    Regardless of the library you're using, the Scala approach is similar to JS approach you provided, you map each of the elements in the array to a copied version of the element that the link element is modified (if you have converted the JsObjects into Scala objects): `objects.map(d => d.copy(link = someValue))` – AminMal May 28 '22 at 03:05

1 Answers1

1

@mysl didn't provide necessary details as mentioned in the comments. So I'm going to speculate that the approach you've proposed didn't work and you want to understand why.

Most probably you've assumed that JsonArray would be mutated when you .map a lambda over it (which is the case for Javascript I guess). That's not true in Scala case. I.e. when you map a list over you've got another list. I.e. .map, as the name assumes, is just a way to map one collection to another.

So what you need to do is:

val originalJsonArray = ...
val updatedJsonArray = originalJsonArray.map { description => 
  description.copy(link = description.link.replace("foo","bar"))
}
println(s"originalJsonArray=$originalJsonArray, updatedJsonArray=$updatedJsonArray") 

I hope that helps, though I'm not sure I guessed your problem correctly.

Sergey Romanovsky
  • 4,216
  • 4
  • 25
  • 27
  • What I needed was to call `collectionAsScalaIterableConverter` on the JsonArray. Then, it got easier for me to read or edit the array of objects. – mysl Jun 02 '22 at 14:59