3

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
1
  • I have posted a proposed solution in the JSONata github issues that takes the form $indexOf(array, searchObject) to return the index if found, or -1 if not found or invalid parameters. Commented Apr 4, 2018 at 20:34

4 Answers 4

2

Try this:

Account.Order ~> $map(function($v, $i) { $v.OrderID = 'order103' ? $i })
Sign up to request clarification or add additional context in comments.

Comments

2

You could merge map's index:

Account.Order ~> $map(function($v, $i) {
  $merge([{'Index': $i}, $v])
})~>function($x){$x[OrderID="order103"].Index}

Comments

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

This is a built in way so should be faster

1 Comment

While Account.Order.OrderID#$i["order103" in $].$i returns 0 Account.Order.OrderID#$i["order104" in $].$i also returns 0 but should be 1
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.