Convert Array String to Comma Separated String
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-05-2023 06:26 PM
Hi,
I have created a Flow action to do a sort on a JSON array from an multi-variable set (MRV). I got it to work, but one of the other stipulations is that I need to turn the values from the sort into a comma separate string.
So my JSON array looks like this.
{
"Provide Drive Label and Size in GBs": [
{
"select_gig_size": "60",
"select_letter": "D"
},
{
"select_gig_size": "100",
"select_letter": "C"
},
{
"select_gig_size": "50",
"select_letter": "G"
}
]
}
I need the select_letter values to look like this: C, D, G
And the select_gig_size values to look like this: 100, 60, 50
This is why I added a sort, so that I can sort by the select_letter. Here is my script.
(function execute(inputs, outputs) {
var mrvs;
var itemID = inputs.record_sysid;
var ritmGR = new GlideRecord('sc_req_item');
if (ritmGR.get(itemID)) {
mrvs = ritmGR.variables[inputs.variable_set_name];
}
var mrvSort = JSON.parse(mrvs);
var sortedArray = mrvSort.sort(function(a, b){
var x = a[inputs.variable_to_sort];
var y = b[inputs.variable_to_sort];
return x < y ? -1 : x > y ? 1 : 0;
});
outputs.sorted_mrv_array = JSON.stringify(sortedArray);
})(inputs, outputs);
The sort works, but I can't seem to convert it from an array to string like in my example above.
Any ideas on how to do this?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-05-2023 07:43 PM
Hi, I suspect your issue is that your array is an array of objects, and so may need to iterate through the sorted array stringifying each element\object and concatenating these individually to your output string.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-05-2023 08:01 PM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-05-2023 08:56 PM
If I have understood your code correctly, then perhaps try something like
var tempString = '';
for(key in sortedArray) {
tempString = tempString + JSON.stringify(sortedArray[key]);
}