Splitting an array of 7, and setting an topic for each message

Hi

I got an function for splitting an array that contains last 7 days of data ( 0-6), where i want the data for the new day like this:

for (let i = 0; i < msg.payload.length; i++) {
    const el = msg.payload[i];
    const entries = Object.entries(el).map(([key, value]) => ({ topic: key, payload: value }));
    node.send([entries]);
}

The result is 7 messages, but no way to split them to process only the last message in next step

How do i set an topic number (or other key 1-7) for each message or an function for only grabbing msg.payload[6] in the function?

You could, but it depends how much work you are prepared to do. :wink:

And as you have written your own node to do it, then you just do what would otherwise be done outside the given split node in that node.

Shouldn't be to difficult, but what is the structure of the incoming message, and how do you want the structure of the returned messages?

Just take the split node - and with a second switch node - you filter the last message with msg.part.index = 6

If you only want the last one - why bother iterate over the array ? just send the last one in the first place ???

1 Like

If you mean how can you request one element by using a topic then you can send the payload through a change node to setmsg.payload[msg.topic] to msg.payload

image

KisYj94CSK

Not sure exactly what you are after but you could do;

As already suggested

const el = msg.payload[6]
const entry = Object.entries(el).map(([key, value]) => ({ topic: key, payload: value }));

return msg

or

for (let i = 0; i < msg.payload.length; i++) {
    const el = msg.payload[i];
    const entries = Object.entries(el).map(([key, value]) => ({ topic: `${key} index ${i}`, payload: value }));
    node.send([entries]);
}

This would give a topic of "key 1" which can be used to select the required msg; or

for (let i = 0; i < msg.payload.length; i++) {
    const el = msg.payload[i];
    const entries = Object.entries(el).map(([key, value]) => ({ topic: key, payload: value }));

    if (i === 6) node.send([entries]);
}

or add a bit to the msg ({ topic: key, payload: value }) becomes ({ topic: key, payload: value, index: i })

Any of these options would allow easy selection of msg 6