jslt icon indicating copy to clipboard operation
jslt copied to clipboard

array indexing: allow array indexing of array literals and for-expressions

Open ecerulm opened this issue 5 years ago • 3 comments

The following expressions are currently incorrect:

[1,2][0]

[for (.object.topics.relatedTopics.list) .element][0]

The only workaround that comes to mind is

let mm = [1,2]
$mm[0]
let xx =  [for (.object.topics.relatedTopics.list) .element]
$xx[0]

This works but it's cumbersome to use in some cases for example:

let object_props = if (.object) (
    
   {
      "category": fallback(.object.category,   [for (.object.topics.relatedTopics.list) .element][0]) // illegal syntax
   }
)
$object_props

then I need to write the let mm= [for (.object.topics.relatedTopics.list) .element] far away from it's use like so

let mm = [for (.object.topics.relatedTopics.list) .element]

let object_props = if (.object) (
    
   {
      "category": fallback(.object.category,  $mm[0])
   }
)
$object_props

because the let expression is not allowed inside the fallback argument list and not allowed inside the if either.

it would be nice to allow indexing directly for-expressions or array literals.

ecerulm avatar Nov 13 '19 16:11 ecerulm

Reading more carefully the Variables documentation it seems that let is allowed in the if and at the beginning of objects.

I was using

let object_props = if (.object) (
   let mm = [for (.object.topics.relatedTopics.list) .element] 
   {
      "category": fallback(.object.category,  $mm[0])
   }
)
$object_props

and that didn't work because of the (...) , if I drop the surrounding (...) like so:

let object_props = if (.object) 
   let mm = [for (.object.topics.relatedTopics.list) .element] 
   {
      "category": fallback(.object.category,  $mm[0])
   }
$object_props

then it works.

Alternatively I see that


let object_props = if (.object) (

   {
   let mm = [for (.object.topics.relatedTopics.list) .element]

      "category": fallback(.object.category,  $mm[0])
   }
)
$object_props

is even more convenient.

In any case, I still think, [for (..) ...][0] should be allowed.

ecerulm avatar Nov 13 '19 17:11 ecerulm

Another workaround is to simply do:

def first(array)
  $array[0]

if (.object) (
   {
      "category": fallback(.object.category,  first([for (.object.topics.relatedTopics.list) .element]))
   }
)

But I agree. It would be nice to support this directly.

larsga avatar Nov 23 '19 12:11 larsga

Saw yet another example of people needing this today:

    def get-ckp()
      let ckp = [for (.identifiers) .[3:] if (starts-with(., "cx"))]
      $ckp[0]

larsga avatar Jun 24 '21 10:06 larsga