Array Index with flow variable

Hi, I am trying to make a flow to read a JSON and write it to a csv file.

The JSON has an object that contains an array and what I am trying to do is to make a loop to write each object of the array in a line of the file.

image

I need to extract in each execution of the node, the data: msg.payload.data.dataList[index].oltId

If in index, I put the value 0, it works correctly, but I want that value to change to extract all the array objects.

The function that I have created has the code:

var listaItems = flow.get('listaItems');

var estado = msg.payload.status;
var api = msg.payload.data.api;
var oltId = msg.payload.data.dataList[listaItems].oltId;
var oltName = msg.payload.data.dataList[listaItems].configuration.oltName;
var oltIP = msg.payload.data.dataList[listaItems].configuration.oltIP;

listaItems --;

flow.set('listaItems',listaItems);

msg.payload.estado = estado;
msg.payload.api = api;
msg.payload.oltId = oltId;
msg.payload.oltName = oltName;
msg.payload.oltIP = oltIP;

return msg;

The error I have is: TypeError: Cannot read property 'oltId' of undefined.

If instead of doing it that way, I simply put a number in the index, it works correctly:

var estado = msg.payload.status;
var api = msg.payload.data.api;
var oltId = msg.payload.data.dataList[0].oltId;
var oltName = msg.payload.data.dataList[0].configuration.oltName;
var oltIP = msg.payload.data.dataList[0].configuration.oltIP;

msg.payload.estado = estado;
msg.payload.api = api;
msg.payload.oltId = oltId;
msg.payload.oltName = oltName;
msg.payload.oltIP = oltIP;

return msg;

How can I use a variable in the array index?.

Thank you very much

Your issue is listitems is 8. ( I am presuming this is what you are using to start your loop. as there is plenty of missing info)
The array starts at 0 and ends at 7
So in your first loop it cann ot read
msg.payload.data.listItems[8].oltId as it does not exist.

Can I just point out that it is not JSON it is a javascript object. JSON is always a string.

This post should help to clarify the difference between Javascript objects and JSON.

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