Identify last column in a CSV

I know the CSV node will use the column names as property names, and column contents as the property values; eg,

msg.payload : Object
object
col1: "first column content"
col2: "second column content"
col3: "third column content"
:
:

And also a list of the column names

columns: "col1,col2,col3,..."

But how would I determine the number of columns?

Or, specifically, determine which is the last column?

You can use the msg.columns and split it to to count the length, or pop() the last element for the name.
e.g.

[{"id":"b3f55db2ad2b7341","type":"inject","z":"65617ffeb779f51c","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":160,"y":1820,"wires":[["dee2d518076c0f3b"]]},{"id":"dee2d518076c0f3b","type":"template","z":"65617ffeb779f51c","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"1,2\n3,4\n","output":"str","x":320,"y":1820,"wires":[["c7e5c56d2b1fa550"]]},{"id":"c7e5c56d2b1fa550","type":"csv","z":"65617ffeb779f51c","name":"","sep":",","hdrin":"","hdrout":"none","multi":"one","ret":"\\n","temp":"","skip":"0","strings":true,"include_empty_strings":"","include_null_values":"","x":470,"y":1820,"wires":[["db78d29828eedd96"]]},{"id":"db78d29828eedd96","type":"function","z":"65617ffeb779f51c","name":"function 22","func":"msg.payload.last = msg.columns.split(\",\").pop()\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":550,"y":1880,"wires":[["5f7fa29e890ddf50"]]},{"id":"5f7fa29e890ddf50","type":"debug","z":"65617ffeb779f51c","name":"debug 242","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":670,"y":1820,"wires":[]}]
msg.payload.last = msg.columns.split(",").pop()
1 Like

From the columns

const realCols = columns.split(',')
const lastCol = realCols[realCols.length - 1]

Or

const realCols = columns.split(',')
const lastCol = realCols.slice(-1)

From msg.payload

const colKeys = Object.keys(msg.payload)
const lastColContent = msg.payload[ colKeys[colKeys.length - 1] ]
// or
const lastColContent1 = msg.payload[ colKeys.slice(-1) ]

There are always multiple ways to do things with JS.

1 Like

Just to note Object.keys sometimes sorts the array.
e.g.

1 Like

I believe that's because you set the keys to be integers. Odd things happen then:

image
image

Bottom line is avoid using integer keys in an object. But yes, you are correct. All versions of JS as far as I know treat the keys in the expected order when they are strings.

Yes I know that, but worth a note as some time i use integer as keys for decimal to string lookup tables.

1 Like

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