How to filter/lookup a value inside an value of an array of objects based on an flow variable?

Currently i am facing to an issue which is related to a lookup function (function or any other node). Therefore i have a "mapping table" which is an array and this array contains objects (configured as a flow variable). The array is looking like this example:

[{"id":"862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0","label":".TEST_1"},
{"id":"689fde57-16c7-405e-a231-b1d821c3bfa6","label":".TEST_2"},
{"id":"0a0923fc-2fa5-4c5b-8a13-1b55d277351d","label":".TEST_3"}]

The upcoming input messages have the following message format:

{
"id":"862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0",
"value":"this is my new value",
"timestamp":"1663864965"
}

The idea was to create a function where the id of the message will be looked up in the array of objects. When the lookup was successfull (match is available) then the label shall be copied to the message. When the lookup was not successfull, the message can be dropped / filtered.

{
"id":"862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0",
"value":"this is my new value",
"timestamp":"1663864965",
"label":".TEST_1"
}

I also tried the JSONata lookup function inside a switch node, but this one does also not work.

Does anybody have an idea how to solve that issue?

You could try a function node:

// const lookup = flow.get("mylookuptable") - if getting it from flow context.
const lookup = [
    { "id": "862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0", "label": ".TEST_1" },
    { "id": "689fde57-16c7-405e-a231-b1d821c3bfa6", "label": ".TEST_2" },
    { "id": "0a0923fc-2fa5-4c5b-8a13-1b55d277351d", "label": ".TEST_3" }
]

const match = msg.payload.id
const check = lookup.filter(e => e.id == match)
if (check.length >0) {
    msg.payload.label = check[0].label
    return msg
}
2 Likes

Welcome to the forum!

You need to re-structure your lookup table for the JSONata $lookup function to work:

[{"id":"862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0",".TEST_1"},
{"id":"689fde57-16c7-405e-a231-b1d821c3bfa6",".TEST_2"},
{"id":"0a0923fc-2fa5-4c5b-8a13-1b55d277351d",".TEST_3"}]
1 Like

Thank you very much for your reply!

I tried your approach including the get command for the flow variable. The function is working out perfectly!

1 Like

I did make a mistake in the array definition above.
It should look like this:

[
   {
       "862277d7-7cb2-4ba3-a6d5-470a9b7a1ff0":".TEST_1"
   },
   {
       "689fde57-16c7-405e-a231-b1d821c3bfa6":
       ".TEST_2"
   },
   {
       "0a0923fc-2fa5-4c5b-8a13-1b55d277351d":
       ".TEST_3"
   }
]

Then it would be (even) simpler if it were an object (and not an array)

1 Like

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