JavaScript Node

This node is used to perform Java / JSON actions. For example, you can parse the output from a previous action, and use it to get the array list of values for a variable, so the user can see the updated information.

The screenshot below illustrates that after getting the user order details from the Fedexlink in the form of variable called ‘orderDetails’, it is fed as the input parameter for the Java node and the script parses to get the next level specific detail from the previous ‘orderDetails’ variable.

Usage Notes :

  • As an output of the Script Node, you can send text messages, carousels, or messages with option prompts. You can also branch the flow based on the script's result.

  • Additionally, the Script Node allows you to set attributes, which can then be used in later steps of the workflow.

JavaScript code generating Rules:

  • Use only var for variable declaration

  • Do not use the arrow function

  • Do not use ES6 conventions

Format for using Built-In variables in the JavaScript Node

var email = flowUser.getEmailId();
return email;

identify the type of the variable in a JavaScript Node

typeof(variable_name) 

Displaying a Message using a Workflow Variable

var displaymessage = 'Hi' + flowUser.getEmailId() + 'How are you ?';
return displaymessage;

Eval Function

return eval('2 + 2');

URL encoding String

function urlEncodeString(str) {
    return escape(str);
}

Anchor tag in JS node

return "<a href=\""+PO_URI+"\">"+PurchaseOrder+"</a>";

Generating Phrases from your Bot

Review the following example to learn how your bot can create phrases using the JavaScript Node.

Given Intent name is: Query Service Orders Available slot variables to be used when creating phrases that will train the Intent and trigger this Intent when the user asks questions that include: anyNumber - captures any number branch - list of branch names date - any date if user asks order - service order can be replace with this variable route - list of routes available

Remember to use the slot variables while generating phrases such as ${slot_variable_name}.

Examples:

  1. user query - view service orders

phrase - view ${order}
  1. user query - view service orders last month from main branch

phrase - view ${order} last month from ${branch} branch
  1. user query - view service orders in august from main branch

phrase - view ${order} in ${date} from $
  1. user query - show service order 213089 details

phrase - show ${order} ${anyNumber} details

Now your bot can generate phrases that use these variables.

Get Intents from Text

Payload

ActionNode

Response

  "intents": [
    {
      "category": "SAP",
      "name": "Query PR / PO / Invoice",
      "id": 350550,
      "confidence": 0.6666667,
      "slots": {
        "invoicePOPR": [
          {
            "id": 1267838,
            "type": "Entity",
            "value": "Purchase Requisition"
          }
        ]
      },
      "requestType": {
        "requestTypeName": "UNKNOWN",
        "score": 0.032144785
      }
    },
    {
      "category": "Aisera System",
      "name": "Help",
      "id": 350523,
      "confidence": 0.5,
      "slots": {},
      "requestType": {
        "requestTypeName": "INFO",
        "score": 0.025648532
      }
    },
    {
      "category": "Ticket Management",
      "name": "Ticket Management : View My Tickets",
      "id": 350538,
      "confidence": 0.5,
      "slots": {},
      "requestType": {
        "requestTypeName": "INFO",
        "score": 0.025648532
      }
    }
  ]
}

Swap Keys and Values in JSON

function swap(json){
  var ret = {};
  for(var key in json){
    ret[json[key]] = key;
  }
  return ret;
}
var json = {
  "a":"1",
  "b":"2",
  "c":"3",
};
return swap(json);

Use application/x-www-form-urlencoded Header

  1. Use the HTTP Action node

  2. Pass the Body (as a String) as a variable to the HTTP request node.

return "grant_type=client_credentials";

LLM Format

{ "Task": "", "InitialRequest": initRequest, "UserConversationHistory": conversationHistory, "Instructions": { "Objective": "", "Rules": [], "Instructions": [], "ResponseFormat": {} } }

JavaScript for an LLM Node

var x = JSON.parse('{}');
var date = new Date();
date = ""+date;
 
x.tenantId = "10000";
x.promptName = "blank_prompt_gpt4_chat_completions";
x.requestParams = [];
var prompt = JSON.parse('{}');
prompt.name = "prompt";
prompt.value = "Act as an SAP Virtual Assist. the user initial request is "+initRequest+". User conversation History is "+conversationHistory+". Today’s date is : "+ date +" Identify the following parameters from conversationHistory and initRequest in order to fill the following JSON.  Return only JSON as Output and nothing else. Output should be in the format - ";
x.requestParams.push(prompt);
x.config = JSON.parse('{}');
x.messages = [];
var messages = JSON.parse('{}');
messages.role = "assistant";
messages.content = "My responseJSON is: ";
x.messages.push(messages);
x.botId = 0;
x.debug = true;
return JSON.stringify(x);

Parsing response:

var message = JSON.parse(response).message;
var answerToUser = JSON.parse(message).answerToUser;
var answerToUser = answerToUser.replace(/\\/g, '');
return answerToUser;

LLM Nearby Restaurant Locations Prompt

Given the provided address: "+address+" If the given address is invalid, set the 'Result' value to 'Invalid address'. If the address is valid, set the 'Result' value to 'Successful' and return a list of nearby famous restaurant locations with the following details: Output format: {  \"Result\": \"str\",  \"restaurant_locations\": [    {      \"distance\": str (distance from given location in miles),      \"duration\": str (travel duration from given location in hours and minutes),      \"name\": str (name of the location),      \"Address\": str (address of the location),      \"image_url\": str (open source image URL from Google of the suggested location)    },    ...  ]}

LLM Nearby Tourist Locations Prompt

Given Address : "+address+" \n If given Address is invalid keep the 'Result' value as 'Invalid address'. \n If both the addresses are valid, Return the 'Result' value as 'Successful'. \n and return nearby famous tourist locations with the below details. Return only output = {\"Result\":str,\"tourist_locations\":[{\"distance\":str(distance from given location in miles),\"duration\":str(travel duration from given location in hours and minutes),\"name\":str(name of the location),\"Address\":str(address of the location),\"image_url\":str(open source image url address from google of the suggested location),\"Location_Homepage_URL\":str(homepage url of the website)},...]}

LLM Nearby Hospital Locations Prompt

Given Address : "+address+" \n If given Address is invalid keep the 'Result' value as 'Invalid address'. \n If both the addresses are valid, Return the 'Result' value as 'Successful'. \n and return nearby famous hospital locations with the below details. Return only output = {\"Result\":str,\"hospitals_locations\":[{\"distance\":str(distance from given location in miles),\"duration\":str(travel duration from given location in hours and minutes),\"name\":str(name of the location),\"Address\":str(address of the location),\"image_u

LLM Distance and Time between 2 locations Prompt

Given Address-1 : "+address1+" and  Address-2 : "+address2+". \n If Address-1 is invalid keep 'Result' value as 'Invalid address-1' and if Address-2 is invalid keep 'Result' value as 'Invalid address-2'. \n If both the addresses are valid, Return the 'Result' value as 'Successful' and calculate 'distance' and 'duration' values by

Analytics

Pie Chart JS Code

function jsonToPieChart(jsonData) {
    // Parse JSON data if it is a string
    var data;
    if (typeof jsonData === 'string') {
        data = JSON.parse(jsonData);
    } else {
        data = jsonData;
    }
    // Ensure the data is an array of objects
    if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') {
        throw new Error('Invalid JSON data provided.');
    }
    // Calculate the total value
    var totalValue = 0;
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var key = Object.keys(item)[0];
        var value = item[key];
        totalValue += value;
    }
    // Create CSS for pie slices
    var pieSlices = '';
    var currentAngle = 0;
    var colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40', '#E91E63', '#00BCD4', '#8BC34A', '#FFC107']; // Colors for each slice
    for (var j = 0; j < data.length; j++) {
        var item = data[j];
        var key = Object.keys(item)[0];
        var value = item[key];
        var sliceAngle = (value / totalValue) * 360;
        var nextAngle = currentAngle + sliceAngle;
       
        pieSlices += colors[j % colors.length] + ' ' + currentAngle + 'deg ' + nextAngle + 'deg, ';
        currentAngle = nextAngle;
    }
    pieSlices = pieSlices.slice(0, -2); // Remove the trailing comma and space
    // Create HTML for pie chart
    var html = '<div class="pie-chart-container">';
    html += '<div class="pie-chart" style="background: conic-gradient(' + pieSlices + ');"></div>';
    html += '<div class="legend">';
   
    for (var k = 0; k < data.length; k++) {
        var item = data[k];
        var key = Object.keys(item)[0];
        var color = colors[k % colors.length];
       
        html += '<div class="legend-item">';
        html += '<span class="legend-color" style="background-color: ' + color + ';"></span>';
        html += '<span class="legend-label">' + key + '</span>';
        html += '</div>';
    }
   
    html += '</div>';
    html += '</div>';
    // Add some basic CSS styles
    html += '<style>';
    html += '.pie-chart-container {';
    html += 'display: flex;';
    html += 'flex-direction: column;';
    html += 'align-items: center;';
    html += '}';
    html += '.pie-chart {';
    html += 'width: 300px;';
    html += 'height: 300px;';
    html += 'border-radius: 50%;';
    html += 'margin: 20px;';
    html += 'position: relative;';
    html += '}';
    html += '.legend {';
    html += 'display: flex;';
    html += 'flex-direction: column;';
    html += 'align-items: flex-start;';
    html += '}';
    html += '.legend-item {';
    html += 'display: flex;';
    html += 'align-items: center;';
    html += 'margin: 5px 0;';
    html += '}';
    html += '.legend-color {';
    html += 'width: 20px;';
    html += 'height: 20px;';
    html += 'border-radius: 50%;';
    html += 'margin-right: 10px;';
    html += '}';
    html += '.legend-label {';
    html += 'font-weight: bold;';
    html += '}';
    html += '</style>';
    return html;
}
// Example usage
var jsonInput = JSON.stringify([
    { "China": 1444216107 },
    { "India": 1393409038 },
    { "United States": 332915073 },
    { "Indonesia": 276361783 },
    { "Pakistan": 225199937 },
    { "Brazil": 213993437 },
    { "Nigeria": 211400708 },
    { "Bangladesh": 166303498 },
    { "Russia": 145912025 },
    { "Mexico": 130262216 }
]);
var pieChartHtml = jsonToPieChart(jsonInput);
return pieChartHtml;

Bar Chart JS Code

function jsonToBarChart(jsonData) {
    // Parse JSON data if it is a string
    var data;
    if (typeof jsonData === 'string') {
        data = JSON.parse(jsonData);
    } else {
        data = jsonData;
    }
    // Ensure the data is an array of objects
    if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') {
        throw new Error('Invalid JSON data provided.');
    }
    // Find the maximum value in the data
    var maxValue = 0;
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var key = Object.keys(item)[0];
        var value = item[key];
        if (value > maxValue) {
            maxValue = value;
        }
    }
    // Create a wrapper div for the bar chart
    var html = '<div class="bar-chart">';
   
    // Calculate bar colors based on value ranges
    var colorRanges = [
        { max: maxValue * 0.5, color: '#4CAF50' },   // Green for lower half
        { max: maxValue * 0.75, color: '#FFC107' },  // Orange for mid range
        { max: maxValue, color: '#FF5722' }          // Red for upper range
    ];
    // Add bars to the chart
    for (var j = 0; j < data.length; j++) {
        var item = data[j];
        var key = Object.keys(item)[0];  // Assuming the first key is the label
        var value = item[key];  // Assuming the value is a number
       
        // Determine color based on value
        var barColor = colorRanges[0].color;  // Default to lowest color
        for (var k = 0; k < colorRanges.length; k++) {
            if (value <= colorRanges[k].max) {
                barColor = colorRanges[k].color;
                break;
            }
        }
        var heightPercentage = (value / maxValue) * 100;  // Calculate height as a percentage of the max value
        html += '<div class="bar" style="height: ' + heightPercentage + '%; background-color: ' + barColor + ';">';
        html += '<span class="value">' + value + '</span>';
        html += '</div>';
    }
    html += '</div>';
    // Add some basic CSS styles
    html += '<style>';
    html += '.bar-chart {';
    html += '    display: flex;';
    html += '    align-items: flex-end;';
    html += '    height: 300px;';  /* Adjust the height as needed */
    html += '    width: 100%;';  /* Adjust the width as needed */
    html += '    border-left: 2px solid black;';
    html += '    border-bottom: 2px solid black;';
    html += '    padding: 10px;';
    html += '    margin: 20px;';
    html += '    box-sizing: border-box;';
    html += '    position: relative;';
    html += '}';
    html += '.bar {';
    html += '    margin: 0 5px;';
    html += '    text-align: center;';
    html += '    width: 50px;';  /* Bar width */
    html += '    position: relative;';
    html += '    display: flex;';
    html += '    align-items: flex-end;';
    html += '    justify-content: center;';
    html += '    transition: height 0.3s ease;';  /* Smooth height transition */
    html += '}';
    html += '.bar:hover {';
    html += '    height: calc(100% + 10px);';  /* Increase height on hover for emphasis */
    html += '}';
    html += '.value {';
    html += '    position: absolute;';
    html += '    bottom: 5px;';  /* Adjust the value position */
    html += '    color: black;';
    html += '    font-weight: bold;';
    html += '}';
    html += '.y-axis-labels {';
    html += '    position: absolute;';
    html += '    left: -30px;';
    html += '    color: black;';
    html += '    bottom: 0;';
    html += '    text-align: right;';
    html += '}';
    html += '.x-axis-labels {';
    html += '    position: absolute;';
    html += '    bottom: -30px;';
    html += '    color: black;';  /* X-axis label text color */
    html += '    width: 100%;';
    html += '    display: flex;';
    html += '    justify-content: space-around;';
    html += '}';
    html += '</style>';
    // Add Y-axis labels and grid lines
    html += '<div class="y-axis-labels">';
    for (var l = 0; l <= 10; l++) {  // Adjust grid lines as needed
        html += '<div style="height: 10%; border-top: 1px solid #ccc;">' + Math.ceil(maxValue / 10) * l + '</div>';
    }
    html += '</div>';
    // Add X-axis labels
    html += '<div class="x-axis-labels">';
    for (var m = 0; m < data.length; m++) {
        var countryName = Object.keys(data[m])[0];
        html += '<div style="width: 50px; text-align: center; color: black;">' + countryName + '</div>';
    }
    html += '</div>';
    return html;
}
// Example usage
var jsonInput = JSON.stringify([
    { "China": 1444216107 },
    { "India": 1393409038 },
    { "United States": 332915073 },
    { "Indonesia": 276361783 },
    { "Pakistan": 225199937 }
]);
var barChartHtml = jsonToBarChart(jsonInput);
return barChartHtml;

Table JS Code

function jsonToHtmlTable(jsonData) {
    // Parse JSON data if it is a string
    var data;
    if (typeof jsonData === 'string') {
        data = JSON.parse(jsonData);
    } else {
        data = jsonData;
    }
    // Ensure the data is an array of objects
    if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') {
        throw new Error('Invalid JSON data provided.');
    }
    // Get table headers from the keys of the first object
    var headers = Object.keys(data[0]);
    // Create HTML table
    var html = '<table border="1">';
    // Add table headers
    html += '<tr>';
    for (var i = 0; i < headers.length; i++) {
        html += '<th>' + headers[i] + '</th>';
    }
    html += '</tr>';
    // Add table rows
    for (var j = 0; j < data.length; j++) {
        html += '<tr>';
        for (var k = 0; k < headers.length; k++) {
            html += '<td>' + data[j][headers[k]] + '</td>';
        }
        html += '</tr>';
    }
    html += '</table>';
    return html;
}
// Example usage
var jsonInput = JSON.stringify([
  {
                "Payment_ID": "1017",
                "Invoice_ID": "5105600120",
                "Status": "Sent",
                "Date_Sent": "2024-06-12",
                "Received_Date": "NA",
                "Vendor_Name": "Cipla Pharma",
                "Amount": "4300.00",
                "Due_Date": "2024-07-11",
                "Payment_Mode": "NA"
            },
    {
                "Payment_ID": "1008",
                "Invoice_ID": "5105600111",
                "Status": "Pending",
                "Date_Sent": "2024-06-10",
                "Amount": "5000.00",
                "Due_Date": "2024-07-11",
                "Payment_Mode": "NA"
            },
  {
                "Payment_ID": "1010",
                "Invoice_ID": "5105600113",
                "Status": "Received",
                "Date_Sent": "2024-05-17",
                "Payment_Mode": "Bank Transfer"
            }
]);
var tableHtml = jsonToHtmlTable(jsonInput);
return tableHtml;

Get User Profile Details Action Node

var userProfile = JSON.parse(userProfile);
var map = new java.util.HashMap();
map.put("firstName",userProfile.identity.firstName);
map.put("lastName",userProfile.identity.lastName);
map.put("email",userProfile.identity.email);
map.put("company",JSON.stringify(Number(userProfile.workInfo.company)));
map.put("country",userProfile.workInfo.location.address.country);
for(var i=0;i<userProfile.customFields.length;i++)
  {
map.put(userProfile.customFields[i].key,userProfile.customFields[i].value);
  }
var rolesArray = [];
for(var i=0;i<userProfile.roles.length;i++)
{
  rolesArray.push(userProfile.roles[i].name);
}
map.put("roles",rolesArray);
return map;

Generate RAG Answer Action

return JSON.stringify({
  "query": question,
  "parameters": {
    "tenant": "Acme",
    "bot": 477
  }
});
//Parsing response
return JSON.parse(response).response

More Examples :

Displaying Information from a Database into a Dynamic Card

For displaying ALL table columns:

var displayedRecords = []; 
var obj = apiairtableurl; 
  for (var i = 0; i < obj.records.length; i++) { var displayedRecord = {}; 
  var record = obj.records[i].fields; 
  displayedRecord["name"] = 'Booking'; 
    for (var key in record) { displayedRecord[key] = record[key]; 
    } 
  displayedRecords.push(displayedRecord); 
  } 
return displayedRecords;

For displaying Specific table columns:

// Assume the API response is stored in a variable called `response`
var response = homescatalog; 
// Initialize a new ArrayList for storing card details 
var cardDetails = new java.util.ArrayList(); for (var i = 0; i < response.records.length; i++) { var record = response.records[i].fields; 
// Create a new HashMap for each house record 
var cardMap = new java.util.HashMap(); 
// Get the details from the record 
var location = record["Location"]; var imageUrl = record["image"]; 
// Assuming the image URL is directly available 
var price = record["Price"]; var description = record["Description"]; var houseName = record["House Name"]; 
// Create the HTML for the image 
var Image = '<img src="' + imageUrl + '">'; 
// Populate the cardMap with details 
cardMap.put("name", houseName); cardMap.put("Location", location); cardMap.put("Image", Image); cardMap.put("Price", price); cardMap.put("Description", description); 
// Add the cardMap to the cardDetails 
ArrayList cardDetails.add(cardMap); } 
// Return the list of card details 
return cardDetails;

For displaying the card Selected by user

return displayedRecords.get(index); 

Current Date format

var today = new Date(); 
var year = today.getFullYear(); 
var month = (today.getMonth() + 1).toString().padStart(2, '0'); 
var day = today.getDate().toString().padStart(2, '0'); 
var formattedDate = year + '-' + month + '-' + day; return formattedDate;

Sample JavaScript: (Support integrations)

var accessToken = CustomerSuccessManagement.get("accessToken");
var url = "https://csmdemodev-dev-ed.my.salesforce.com/services/data/v45.0/query/?q=Select+Id%2C+name%2C+AccountId%2C+Status%2C+OrderNumber%2C+TotalAmount+from+Order";
print("token:" + accessToken);
var resp = httpGet(url, "application/json", accessToken).data;
return resp;
/*************
Utils
*************/
function httpGet(theUrl, contentType, token){
    var con = new java.net.URL(theUrl).openConnection();
    con.requestMethod = "GET";
    con.setRequestProperty("Content-Type", contentType);
    con.setRequestProperty("Authorization", "Bearer " + token);
    return asResponse(con);
}
function httpPost(theUrl, data, contentType){
    contentType = contentType || "application/json";
    var con = new java.net.URL(theUrl).openConnection();
    con.requestMethod = "POST";
    con.setRequestProperty("Content-Type", contentType);
    // Send post request
    con.doOutput=true;
    write(con.outputStream, data);
    return asResponse(con);
}
function asResponse(con){
    var d = read(con.inputStream);
    return {data : d, statusCode : con.responseCode};
}
function write(outputStream, data){
    var wr = new java.io.DataOutputStream(outputStream);
    wr.writeBytes(data);
    wr.flush();
    wr.close();
}
function read(inputStream){
    var inReader = new java.io.BufferedReader(new java.io.InputStreamReader(inputStream));
    var inputLine;
    var response = new java.lang.StringBuffer();
    while ((inputLine = inReader.readLine()) != null) {
           response.append(inputLine);
    }
    inReader.close();
    return response.toString();
}

Adding Dyanmic Arraylist(as String) to JSON Body

var pr_line_items = new java.util.ArrayList();
return pr_line_items;

pr_line_items.add(JSON.stringify(
      {
        "PurchaseRequisitionType": "Item_Category",
        "to_PurchaseReqnAcctAssgmt": {
          "results": [
            {
                "GLAccount": "GLAccount"
            }
          ]
  }
      }));
return pr_line_items;

pr_line_items.add(JSON.stringify(
      {
        "PurchaseRequisitionType": "Item_Category2",
        "to_PurchaseReqnAcctAssgmt": {
          "results": [
            {
                "GLAccount": "GLAccount2"
            }
          ]
  }
      }));
return pr_line_items;

return JSON.stringify({
  "PurReqnDescription": "PurReqnDescription",
  "to_PurchaseReqnItem": {
    "results": JSON.parse(pr_line_items)
  }
}); 

ArrayList for Airtable Listing Records

var arr = new java.util.ArrayList();
var records = response.records;
for(var i=0;i<records.length;i++)
  {
var map = new java.util.LinkedHashMap();
var fields = records[i].fields;
map.put("",fields.);
map.put("",fields[""]);
arr.add(map);
  }
return arr;

Date Format

  var d = new Date(date);
  var year = d.getUTCFullYear();
  var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var daySuffix = getOrdinalSuffix(d.getDate());
  //return dayNames[d.getDay()]+"," +" "+d.getDate()+ daySuffix+" " + monthNames[d.getMonth()] + " "+year;
  return  monthNames[d.getMonth()]+" "+ d.getDate() + ", "+year;
}
function getOrdinalSuffix(day) {
  switch (day % 10) {
    case 1:
      return "st";
    case 2:
      return "nd";
    case 3:
      return "rd";
    default:
      return "th";
  }
}
function getHoursAndMinutesIn12HourFormat(date) {
  var d = new Date(date);
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var ampm = hours >= 12 ? "PM" : "AM";
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  return hours +":"+minutes+" "+ ampm;
}
function getDateFormat(str,withTime)
{
  if (withTime)
  return printDate(new Date(str))+" "+getHoursAndMinutesIn12HourFormat(new Date(str));
  else
return printDate(new Date(str));
}

Amount in US Format

function formatNumberToUS(amount) {
    var numArray = amount.split('');
    var decimalIndex = numArray.indexOf('.');
    if (decimalIndex === -1) {
        decimalIndex = numArray.length;
    }
    var formattedNumber = [];
    var count = 0;
    for (var i = decimalIndex - 1; i >= 0; i--) {
        formattedNumber.unshift(numArray[i]);
        count++;
        // Insert a comma every three digits, except for the first group
        if (count % 3 === 0 && i !== 0) {
            formattedNumber.unshift(',');
        }
    }
    if (decimalIndex < numArray.length) {
        formattedNumber.push('.');
        for (var j = decimalIndex + 1; j < numArray.length; j++) {
            formattedNumber.push(numArray[j]);
        }
    }
    return formattedNu

Date to Epoch

return Number(new Date()); 

sTable Formatting from JSON in JS Node

function jsonToHtmlTable(jsonData) {
    // Parse JSON data if it is a string
    var data;
    if (typeof jsonData === 'string') {
        data = JSON.parse(jsonData);
    } else {
        data = jsonData;
    }
    // Ensure the data is an array of objects
    if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') {
        throw new Error('Invalid JSON data provided.');
    }
    // Get table headers from the keys of the first object
    var headers = Object.keys(data[0]);
    // Create HTML table
    var html = '<table border="1">';
    // Add table headers
    html += '<tr>';
    for (var i = 0; i < headers.length; i++) {
        html += '<th><b>' + headers[i] + '</b></th>';
    }
    html += '</tr>';
    // Add table rows
    for (var j = 0; j < data.length; j++) {
        html += '<tr>';
        for (var k = 0; k < headers.length; k++) {
            var cellData = data[j][headers[k]];
            html += '<td>' + (cellData != null ? cellData : '') + '</td>';
        }
        html += '</tr>';
    }
    html += '</table>';
    return html;
}
// Example usage
var jsonInput = JSON.stringify([ {
                "Payment_ID": "1017",
                "Invoice_ID": "5105600120",
                "Status": "Sent",
                "Date_Sent": "2024-06-12",
                "Received_Date": "NA",
                "Vendor_Name": "Cipla Pharma",
                "Amount": "4300.00",
                "Due_Date": "2024-07-11",
                "Payment_Mode": "NA"
            },
            {
                "Payment_ID": "1011",
                "Invoice_ID": "5105600114",
                "Status": "Received",
                "Date_Sent": "2024-05-17",
                "Received_Date": "2024-06-13",
                "Vendor_Name": "Cipla Pharma",
                "Amount": "3100.00",
                "Due_Date": "2024-07-11",
                "Payment_Mode": "Credit Card"
            },
            {
                "Payment_ID": "1005",
                "Invoice_ID": "5105600108",
                "Due_Date": "2024-07-17",
                "Payment_Mode": "Credit Card"
            }
            ]);
var tableHtml = jsonToHtmlTable(jsonInput);
return tableHtml;

Random Number Generator

function generateTicketCode() {
    var prefix = "INC";
    var randomNumber = Math.floor(100000 + Math.random() * 900000);
    return prefix+""+randomNumber;
}

FlattenJSON from given ArrayList

function flattenJson(input) {
    var flatRecord = {};
    function flattenObject(obj, parentKey) {
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                var propName = parentKey ? parentKey + '_' + key : key;
                if (typeof obj[key] === 'object' && obj[key] !== null) {
                    flattenObject(obj[key], propName);
                } else {
                    flatRecord[propName] = obj[key];
                }
            }
        }
    }
    flattenObject(input, '');
    return flatRecord;
}

Join Array with Commas

function joinArrayWithComma(arr)
{
    let result = '';
    for (let i = 0; i < arr.length; i++)
    {
        result += arr[i];
        if (i < arr.length - 1)
        {
            result += ',';
        }
    }
    return result;
}

Unique Array while Iterating through JSON

var uniqueArray = [];
var records = json.records;
for(var i=0;i<records.length;i++)
  {
var field = records[i].fields;
if(uniqueArray.indexOf(field.Golf_Course_Name)==-1)
uniqueArray.push(field.Golf_Course_Name);
  }
return uniqueArray;

Last updated