Convert object to string

Hi evereyone, I trying to figure out how to format may payload output like this { S1: "A", S2: "C" } to "A,C".
I tried to code in a function

var myJSON = msg.payload;
var str = JSON.stringify(myJSON);
return str;

But not the output I was expecting.

Try

var str = JSON.stringify(Object.values(myJSON));

Hi.. this is my output of my new version using the code suggested [2,3,"A,0",1] but I noticed it is not in the right order should be ["A,0",1.2,3] what do you think causes it and my end goal is to have it this format when placed in a variable str1 = "A,0,1,2,3" I tried to come up with a solution but no avail.

What exactly was the value of msg.payload you had to get this result?

I'm getting this value in the debug {"S1":"A,0","S2":1,"S3":2,"S4":3}

If S1 and S2 are always the keys to use then add a function nodes and so this...

let data = msg.payload;
let arr = [data.S1, data.S2];
msg.payload = arr.join(",");
return msg;

If you are saying there are a variable amount of S1, S2, S3...Sn then

let data = msg.payload;
let i = 1;
let arr = [];
while(data["S"+i] != null) {
  arr.push(data["S"+i]);
  i++;
}
msg.payload = arr.join(",");
return msg;

EDIT - updated (added the important i++ - oops)

2 Likes

@Steve-Mcl thanks.. I will give it a try.

kind regards,
Joe

@Steve-Mcl..works great, thank you for the effort and saving the time! :+1:

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