Reputation: 421
JSONata provides several functions to operate on array contents. However, I am at a loss to determine how to return the index of a found element (similar to the Array.indexOf function in JavaScript). I'm looking for something like:
$indexOf(Account.Order[OrderID="order103"])
or
Account.Order.indexOf(OrderID="order103")
or
Account.Order[OrderID="order103"].index
Upvotes: 2
Views: 4508
Reputation: 111
Accout.Order.OrderId#$i["order103" in $].$i
This is a built in way so should be faster
Upvotes: 1
Reputation: 421
Neither proposed solution ensured a valid response if not found but adding the additional test seems to do what I'd expected:
($x:=Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order101' ? $i });
$exists($x)?$x:-1)
will return -1
($x:=Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order103' ? $i });
$exists($x)?$x:-1)
will return 0
($x:=Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order104' ? $i });
$exists($x)?$x:-1)
will return 1
Upvotes: 0
Reputation: 1559
Try this:
Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order103' ? $i })
Upvotes: 2
Reputation: 5217
You could merge map's index:
Account.Order ~> $map(function($v, $i) {
$merge([{'Index': $i}, $v])
})~>function($x){$x[OrderID="order103"].Index}
Upvotes: 2