wnm3
wnm3

Reputation: 421

How to get index of element in array in JSONata

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

Answers (4)

Saqib Shakil
Saqib Shakil

Reputation: 111

Accout.Order.OrderId#$i["order103" in $].$i

This is a built in way so should be faster

Upvotes: 1

wnm3
wnm3

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

Andrew Coleman
Andrew Coleman

Reputation: 1559

Try this:

Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order103' ? $i })

Upvotes: 2

tonymayoral
tonymayoral

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

Related Questions