Skip to content
ENG

Index selector

Given the following input payload:

[
1,
3,
{
"number": 9
},
12,
15
]

Write a DataWeave transformation that produces the following output:

9
  • Remember that to get a value with the Index selector [<n>] you have to pass the index of the position you want. E.g. index 0 = position 1, index 1 = position 2, and so on.
  • Since the expected value sits inside an object, you can use the Single-value selector . to get it.

🔒🔓Show solution
%dw 2.0
output application/json
---
payload[2].number

Notes:

  1. Since the value we want sits in position 3, we have to reach index 2.
  2. As an object is returned, we use the number key to get its value.
  3. Other solutions could be:
  • payload.number[0]: because using the single-value selector inside an Array returns every matching key of the objects, so it returns a new Array with the values under the number key; then index 0 is taken, since it is the only position holding a value.
  • payload[2][0]: getting the second index returns a one-key object, and using the index selector again with index 0 also reaches that value without having to name the number key.
{Code mat;}

Learn MuleSoft: courses, exercises and quizzes. Free, no sign-up.