Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of JsObjects in a JsValue?

In Play! (2.2-M2) I have a JsValue similar to:

val people: JsValue = [{"name":"Alice","subdomain":"alice","color":"orange"},{"name":"Jorge","subdomain":"jorge","color":"blue"},{"name":"Bob","subdomain":"robert","color":"green"}...]

I just want the number of elements in this JsValue. I can get it, clunkily, through

(people \\ "name").size

but this size calculation sits inside a method that receives JsValues with different content, and name won't always be present, like

val places: JsValue = [{"country":"UK", "country":"ES", ...]

or

val things: JsValue = [{"widget":"foo", "price":"1", "widget":"bar" ... ]

I'm pulling my hair out, how do I just get the number of elements in these JsValues?

like image 811
JennyDanger Avatar asked Aug 13 '13 14:08

JennyDanger


1 Answers

If you want to count the number of objects inside the array, you can map it to a JsArray.

people.as[JsArray].value.size or people.asOpt[JsArray].map(_.value.size).

like image 108
Marius Soutier Avatar answered Nov 04 '22 10:11

Marius Soutier