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!

2
  • 2
    Which library are you using? Commented May 28, 2022 at 2: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)) Commented May 28, 2022 at 3:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What I needed was to call collectionAsScalaIterableConverter on the JsonArray. Then, it got easier for me to read or edit the array of objects.

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.