How to always use the last item in an array?

I have a switch node where I check a value. Feeding into this switch node is an array.

Sometimes the array consists of 1 item, sometimes 2, sometimes 3, etc.

How can I make the switch node always check the last item in the array for the value?

Instead of specifying the number. For example: payload.example[1].customer.firstName or payload.example[2].customer.firstName.

It would always check #2 if the array had 2, always check #4 if the array had 4.

Did that make sense?

You can use JSONata in the property field.
e.g.

[{"id":"c828b9168a3f213f","type":"inject","z":"da8a6ef0b3c9a5c8","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"example\":[{\"customer\":{\"firstName\":\"tom\"}},{\"customer\":{\"firstName\":\"dick\"}},{\"customer\":{\"firstName\":\"harry\"}}]}","payloadType":"json","x":250,"y":3100,"wires":[["51466519ddf4a14b"]]},{"id":"51466519ddf4a14b","type":"switch","z":"da8a6ef0b3c9a5c8","name":"","property":"$$.payload.example[-1].customer.firstName","propertyType":"jsonata","rules":[{"t":"eq","v":"harry","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":430,"y":3080,"wires":[["a81d87f562b74deb"]]},{"id":"a81d87f562b74deb","type":"debug","z":"da8a6ef0b3c9a5c8","name":"debug 225","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":650,"y":3120,"wires":[]}]
$$.payload.example[-1].customer.firstName
1 Like

The traditional way is to do:

payload.example[payload.example.length - 1].customer.firstName

But a more modern way is to:

payload.example.slice(-1)[0].customer.firstName

Or:

payload.example.pop().customer.firstName

Though that actually does change the original which is probably not what you want.

Or even:

const [last,] = payload.example.reverse()
console.log(last.customer.firstName)

But if you can cope with only the very latest version of JS (needs node.js v16.6+):

payload.example.at(-1).customer.firstName
1 Like

I copied your example flow, but it outputs the whole array through the switch node?

First one returns nothing, the second one gives the following error:

Invalid JSONata expression: Attempted to invoke a non-function

Then the data you listed isn't what you are trying to handle. In any case, that is the correct syntax, you simply need to adapt it to your data.

Again, almost certainly your data isn't what you assume (or you are using an old, outdated version of node.js):
image

I answered this question, you never asked to output the last value.

Please be specific, what do you actually require

Ah, I understand now, you were asking about a switch node not about JavaScript. Obviously I was giving you the JavaScript code.

Sorry my bad, this was exactly the solution I was looking for. Thank you.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.