Search code examples
jsonata

How to autoincrement global variable in jsonata


(
    $find := function($object, $data) {(
        $count := 1;
        $each($object, function($v, $k){(
            $k in $data ? ($count := ($count + 1)): ''
        )})
    )};
)

Here count is always returning 2, how to auto increment variable in jsonata.


Solution

  • As far as I know, it's impossible in JSONata to reassign a value of a variable defined in a parent closure, meaning that the only way to deliver its increment from the inner closure to the outer closure is to return it from your function. $each is not supposed to return anything, but we can always use $reduce for that - something like below:

    (
      $find := function($object, $data) {
        (
          $count := $reduce($keys($object), function($acc, $k) { 
            $k in $data ? ($acc + 1) : $acc
          }, 0);
    
          $count
        )
      };
    
      $find($, ["destination", "line_items"])
    )
    

    Interactive playground link: https://stedi.link/syBM3yM