Allocate ID or a leading number to csv import

Hello!

I have a CSV file with about 1000 rows and 2 columns.

col1 col2

Is it possible that each line is given an ID or a leading number when importing.

Example.

Line 1: col1 col2 1
Line 2: col1 col2 2
Line 3: col1 col2 3

He should write the leading number in an object.

you can use javascript's map command and add the id in the array of objects

msg.payload = msg.payload.map((el, index) => { return { id: index + 1, ...el } }) return msg;

Example Flow:

[{"id":"5a497eb3900dcd92","type":"inject","z":"54efb553244c241f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":350,"y":840,"wires":[["7dc1c5b4e73b459f"]]},{"id":"5f9fbd8a7188b524","type":"csv","z":"54efb553244c241f","name":"","sep":",","hdrin":"","hdrout":"none","multi":"mult","ret":"\\n","temp":"col1,col2","skip":"0","strings":true,"include_empty_strings":"","include_null_values":"","x":710,"y":840,"wires":[["1afc916faaef506b"]]},{"id":"7dc1c5b4e73b459f","type":"template","z":"54efb553244c241f","name":"","field":"payload","fieldType":"msg","format":"text","syntax":"mustache","template":"1,2\n11,22\n111,222\n1111,2222","output":"str","x":520,"y":840,"wires":[["5f9fbd8a7188b524"]]},{"id":"1bb9aa311187c971","type":"debug","z":"54efb553244c241f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":1030,"y":840,"wires":[]},{"id":"1afc916faaef506b","type":"function","z":"54efb553244c241f","name":"","func":"msg.payload = msg.payload.map((el, index) => { return { id: index + 1, ...el } })\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":860,"y":840,"wires":[["1bb9aa311187c971"]]}]

Hello!

Thank you so much for the answer.

that works great. Is it possible to add the total number of lines to it?

1/1000
2/1000
3/1000
...

Sure ..

let total = msg.payload.length; 
msg.payload = msg.payload.map((el, index) => { return { id: index + 1, ...el, length: total  } })

Thank you very much for that.

you are welcome ..

some information on the methods used

Array.prototype.map()

... spread syntax

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