Documentation
AcademyCommunitySign In
  • 👋Overview
  • 💙Platform Features
  • Getting started
    • 🚪Signing up & Logging in
      • 👤Profile Settings
    • 🎛️App Management
    • ✴️Templates to Start With
      • Basic Template (Blank app)
      • CRM Template
    • 👨‍🎓Learning Directual
      • 👨‍🏫Webinars
  • Data base
    • Data Structures
      • System Structures
    • Data Types
      • Markdown Cheat Sheet
      • Indexing Fields
      • Formatting Date/Time
    • Directual Query Language (DQL)
    • Import and Export
      • Import API
    • File Storage
      • API for File Storage
  • API and integraions
    • API-Endpoints
      • Advanced techniques for GET and POST requesting
        • Paging for GET-requests
        • Dynamic sorting for GET-requests
        • Custom filtering parameters for GET-requests
        • Advanced filtering for GET-requests
        • Formatting response for GET-request
        • Fields validation for POST-requests
        • Synchronic scenarios for POST-requests
        • Cross-Origin Resource Sharing CORS
      • API testing and debugging
      • Coding mode (raw mode) in filters
      • Swagger specification
    • Webhooks
    • Authentication API
      • Login/password
      • OpenID connect
      • Facebook oAuth
      • Google oAuth
    • Security Features
    • Other Integrations
      • OpenAI
      • Integration Hubs
        • Zapier
      • Telegram
        • Telegram: Advanced Techniques
      • Email
        • SMTP
        • Gmail
      • Twilio SMS
      • Airtable
      • Coupler.io
      • Other No-Code Tools
        • Bubble.io
          • Authorization
          • Displaying Data from Directual on Bubble
        • Adalo
        • UI bakery
        • Tilda
        • AppGyver
  • App interface
    • Web-App Builder basics
    • Web-App Settings
      • General web-app settings
      • Main menu
      • Creating a logotype
      • Web-App color scheme
      • Web-app typography
      • White Labeling
      • Web-App Icon
      • Custom Domain
      • Custom code
    • Setting Up Page Layout
      • Subpages and URL Parameters
    • Components
      • Multistep Form
      • Cards
      • Table
      • Kanban
      • Chart
      • Markdown text
      • HTML code
      • Hint
      • Link Button
      • Video
      • Form (outdated)
    • Embedding Pages
  • Scenarios
    • Understanding Directual Scenarios
      • Directual Event Model
    • Event-Based Triggers
    • Scheduled Triggers
      • Cron Format
    • Synchronous Scenarios
    • Editing Scenarios
      • System Steps
        • Start step
        • Delay step
        • Comment step
        • Catch error step
        • Link scenario step
        • Exit step
      • Action steps
        • Edit object step
        • Create object step
        • Search objects step
        • JSON step
        • Delete object step
        • Run report step
        • Generate document step
        • JS SDK step
      • Condition steps
        • Condition step
        • A/B test step
        • JS SDK condition step
      • Integration steps
        • HTTP-request step
        • Zapier step
        • Telegram step
        • API response
        • Email step
        • SQL-request step
        • Queue step
    • Using Variables
      • Global Variables
      • Context Variables (scenario parameters)
    • Testing and Debugging
    • System Scenarios
    • Advanced Scenario Settings
  • Template system
    • Templating Principles
      • Templating Techniques for Scenarios
      • Templating Techniques for Web-pages
    • Coding Mode (evaluating as a JS-expression)
    • Comparison Component
      • Regular Expressions
    • Tips for Dealing with Data
  • Telegram
    • Telegram
  • Plugins
    • 🔌Using Plugins
      • Scenario Steps Plugins
      • Web Plugins
      • User Authentication Plugins (Not Web3)
        • TMA (Telegram Mini App)
        • Google OAuth Plugin
        • Facebook OAuth Plugin
        • Open ID Auth Plugin
      • Blockchain (Web3)
        • TON (The Open Network)
        • Polygon
        • Ethereum
        • NEAR Protocol
        • NFT and Smart-Contracts
        • MetaMask Wallet
        • WalletConnect
      • WebSockets (Socket.IO)
    • 🪚Developing Plugins
      • Developing Scenario Plugins
      • Developing Web-plugins
        • Example: Using Chart.js in Directual
        • Example: Building Simple Form
        • Example: TON plugin
  • Teams
    • Teams
    • Sandbox Apps
  • JavaScript SDK
    • Directual + JavaScript SDK: The Basics
    • Internal $D Methods
    • Using Google Sheets
    • JS SDK: Examples
  • Reports
    • Reports
  • App life cycle management
    • App Versions
  • Directual 💙 React JS
    • Directual + React JS
  • Pricing and billing
    • 💳How Billing Works
    • 🎁Promo Codes
    • Pricing Plans for Apps
    • Team Pricing Plans
    • How we count requests and operations
    • On-Demand Resource Consumption
    • 🤝Affiliate Program
  • Hire a Directual expert
    • 🏆Certification
    • 🤝Matching with Experts
    • 🏦Escrow service
  • Security and stability
    • 🛡️Public Cloud
    • Platform Architecture
  • Support
    • 📬Contact Directual
  • Directual step-by-step
    • Public Development Roadmap
      • Step 0: Planning App Architecture
      • Step 1: Requesting Features
      • Step 2: Approving Features
      • Step 3. Upvoting Features
      • Step 4. Watching Features
    • Weather Forecast App
    • Web3 Marketplace on Polygon
    • Transferring NFT
Powered by GitBook
On this page
  • 🔢 Dealing with numbers and decimals
  • Getting a random number [1–100]
  • Changing the number of digits to appear after the decimal point
  • 🔤 Dealing with strings
  • Converting multiline text to an array of lines
  • Getting md5 hash
  • Generating a random string (password)
  • 🛒 Dealing with arrays
  • Converting a string (Directual array or arrayLink) into a JS-Array value
  • Saving a JS array to a Directual array
  • Counting elements of an array
  • Getting an element from an array with number N
  • Getting a random element from an array
  • Adding an element into an array while preventing duplicates
  • Removing an element from an array
  • Applying an array iterator map()
  • Applying an array iterator reduce() for calculating average
  • Arrays intersection (using lodash)
  • 📅 Dealing with dates
  • Getting current time
  • Converting date format
  • Converting into timestamp
  • Parsing date
  • Incrementing date
  • Creating a unique object for each day
  • Calculating the number of days between two dates
  • Applying MomentJS
  • 🥷 Regular expressions
  • Replace
  • Extract

Was this helpful?

  1. Template system

Tips for Dealing with Data

Cheat sheet for Makers 💁‍♂️

PreviousRegular ExpressionsNextTelegram

Last updated 1 year ago

Was this helpful?

Don't forget to turn on ✅ option

🔢 Dealing with numbers and decimals

Getting a random number [1–100]

Math.floor(Math.random()*100)

Changing the number of digits to appear after the decimal point

parseFloat('{{decimal_value}}').toFixed(2) // 2 digits after the point
//
// e.g.
// parseFloat('12.438324').toFixed(2) returns 12.43

🔤 Dealing with strings

Converting multiline text to an array of lines

For instance, if you receive a {{text}} field (type: string) from a Telegram bot in multiple lines and want to process each line separately, here's how you can do it:

'{{text}}'.replace(/\n/g, ',') 
// this is string with lines, separated by commas (you may use any other character)
// in this way arrays in the platform are stored
// e.g.
// {{text}} = 
// Good fortune? The fact is
// The more that you practise
// The harder you sweat
// The luckier you get
// 
// result will be:
// Good fortune? The fact is,The more that you practise,The harder you sweat,The luckier you get

'{{text}}'.replace(/\n/g, ',').split(',') // this returns js-array

'{{text}}'.replace(/\n/g, ',').split(',')[0] // this returns the first line
'{{text}}'.replace(/\n/g, ',').split(',')[1] // this returns the second line

Getting md5 hash

$D.md5('{{string}}')
//$D.md5('12345') returns 827ccb0eea8a706c4c34a16891f84e7b

Generating a random string (password)

Math.random().toString(36).slice(-12) // 12 characters string

🛒 Dealing with arrays

Directual stores array and arrayLink types as strings

Converting a string (Directual array or arrayLink) into a JS-Array value

'{{array}}'.split(',')
// {{array}} is a field with Directual type array
// 
// e.g. {{array}} = 1,-2,a
// '{{array}}'.split(',') returns [1,-2,a]

Saving a JS array to a Directual array

const array = ["a","b","c"] // standard JS array
// if you want to save it to Directual array, you need:
array.join(",")
// as soon as Directual stores array and arrayLink types as strings

Counting elements of an array

// basically, the expression is
'{{array}}'.split(',').length
// {{array}} is a field with Directual type array

// BUT! if {{array}} is empty, the expression above returns 1,
// so the expression should be the following:
'{{array}}' ? '{{array}}'.split(',').length : 0

Getting an element from an array with number N

'{{array}}'.split(',')[N]
// {{array}} is a field with type Array.
// 
// e.g. {{a}} = a,b,c
// '{{a}}'.split(',')[1] returns b

Getting a random element from an array

'{{array}}'.split(',')[Math.floor(Math.random()*'{{array}}'.split(',').length)]
// here we counts N = number of elements in array, 
// get the random number [0–N] and pick the random element

Adding an element into an array while preventing duplicates

$D.concat('{{array}}', 'new element')
// or
$D.concat('{{array}}', '{{other_field}}')
// even or
$D.concat('{{array}}', '{{other_field_1}},{{other_field_2}}')
//
// e.g.
// $D.concat('', '3') returns 3
// $D.concat('1,2', '1,2,3') returns 1,2,3
// $D.concat('1,2,3', '3,4') returns 1,2,3,4
// $D.concat('1,2,3', '3') returns 1,2,3

Removing an element from an array

$D.splice('{{array}}', 'removed element')
// or
$D.splice('{{array}}', '{{other_field}}')
// even or
$D.splice('{{array}}', '{{other_field_1}},{{other_field_2}}')
//
// e.g.
// $D.splice('', '3') returns ''
// $D.splice('1,2', '1,2,3') returns 3
// $D.splice('1,2,3', '3,4') returns 1,2
// $D.splice('1,2,3', '3') returns 1,2

Applying an array iterator map()

// e.g. we want to add ' is the best' to every element of {{array}}.
// Here is the expression for that:
'{{array}}'.split(',').map(function(element) 
   {return element + ' is the best'}).join(',')
   
// let {{array}} was "Jhon,Ivan,Anna"
// the expression will return
// Jhon is the best,Ivan is the best,Anna is the Best

Applying an array iterator reduce() for calculating average

"{{array}}".split(",")
    .reduce(function(acc, curr) 
        {return parseInt(acc) + parseInt(curr)}) 
    / "{{array}}".split(",").length
    
// e.g. for {{array}} == 1,2,5,0,-4,12 
// that expression returns 2.666667

Arrays intersection (using lodash)

_.intersection("{{array1}}".split(","), "{{array2}}".split(","));

📅 Dealing with dates

Getting current time

The method (new Date()).toISOString() returns a JS-date-object with current time. This method is more useful than now, because we can compose complex JS-expressions in a one step using (new Date()).toISOString()

(new Date()).toISOString()
// returns current Coordinated Universal Time (UTC)
// (new Date()).toISOString() === now === moment().toISOString()

Converting date format

$D.date.format returns string data, so you can't save the result into a field type of date.

$D.date.format('{{date_1}}','MMMM dd, YYYY')
// 
// e.g. $D.date.format('2020-05-20T18:14:11.000Z','MMMM dd, YYYY') 
// returns May 20, 2020
//
$D.date.format($D.date.new(),'dd/MM/YYYY')
// returns today in a certain format e.g. 07.01.2021

Converting into timestamp

Unix timestamp format is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC.

((new Date('{{date}}')).getTime()/1000).toString()
//
// e.g {{date}} == 2020-11-12T00:00:00
// ((new Date('{{date}}')).getTime()/1000).toString() returns 1605139200 seconds

Parsing date

$D.date.parse('{{formatted_date}}',dateFormat)
// 
// e.g. $D.date.parse('10-03-2020','dd-MM-YYY') returns 2020-03-10T00:00:00.000Z

You can compose an expression using both $D.date parse and $D.date.format to convert a format date from one to another:

$D.date.format($D.date.parse('10-03-2020','dd-MM-YYY'),'MMMM dd, YYYY')
// here we've converted 10-03-2020 into March 10, 2020

Incrementing date

If you want to add minutes/hours/days/weeks to the date, here is the way

//adding {{minutes}} minutes
(new Date((new Date('{{date}}')).getTime() + ('{{minutes}}' * 60 * 1000))).toISOString()

//adding {{hours}} hours
(new Date((new Date('{{date}}')).getTime() + ('{{hours}}' * 60 * 60 * 1000))).toISOString()

//adding {{days}} days
(new Date((new Date('{{date}}')).getTime() + ('{{days}}' * 60 * 60 * 24 * 1000))).toISOString()

//adding {{weeks}} weeks
(new Date((new Date('{{date}}')).getTime() + ('{{weeks}}' * 7 * 60 * 60 * 24 * 1000))).toISOString()

Creating a unique object for each day

You may need to aggregate statistics for the day into a single object (e.g., counting the quantity of orders or users). A straightforward approach is to create an object with an ID in the format of the date of the day. Here's an example expression for generating such a day-unique ID:

$D.date.format($D.date.new(),'dd-MM-YYYY')
// for todays object

$D.date.format('{{today_date}}','dd-MM-YYYY')
// where {{today_date}} is a type of date field

Don't forget to Save a link (write a link in the field) to the new object in order to be able to edit it. Note, that if you create an object with ID while there is an object with such an ID, nothing will be broken. You'll just create a link to that existing object.

Calculating the number of days between two dates

To solve this, use the getTime() JS-function, which operates on the Date JS-object and returns Milliseconds since Epoch time. Here are the steps:

  • Getting a Date JS-object applying new Date('{{date}}') to the field {{date}} type of date

  • Getting the value in milliseconds since Epoch time applying .getTime()

  • Calculate the difference between two dates in milliseconds

  • Convert milliseconds into days, dividing the result to (1000*60*60*24)—1000 milliseconds in a one, second; 60 seconds in a minute; 60 minutes in an hour; and 24 hours in a day

Math.floor((($D.date.new().getTime() -
 (new Date('{{date}}')).getTime()))/(1000*60*60*24))
// Calculating the number of days between the current moment and {{date}}

Math.floor((((new Date('{{date_1}}')).getTime() -
 (new Date('{{date_2}}')).getTime()))/(1000*60*60*24))
// Calculating the number of days between {{date_1}} and {{date_2}}

Applying MomentJS

Example of using MomentJS:

moment("{{date}}").add(10, 'days').format('DD-MM-YYYY')

// e.g {{date}} == 2020-11-12T00:00:00
// expression will return 22-11-2020

🥷 Regular expressions

Directual JS-engine supports Regex-functions. Here are some widespread examples.

Replace

"{{text}}".replace(/one/gm, "two") 
// repplaces all the words "one" in the text to "two"

Extract

/\+\d{11}/gm.exec("{{text}}") // returns an array of phone numbers found in text
/\+\d{11}/gm.exec("{{text}}")[0] // the first element of an array
/\+\d{11}/gm.exec("{{text}}").join(",") // converts JS-array into Directual-array

$D.concat is a specific

$D.splice is a specific

JS iterators are more applicable in . However, .map iterator can be useful in regular steps as well. This method adits all the elements of a given array.

JS iterators are more applicable in . However, .reduce iterator can be useful in regular steps as well.

on _.intersection

Learn more about

You can also for that

N.B Here is a nice article referring to

You can also use MomentJS library. Check out .

Tip: use for composing a correct Regex-expression

Directual JS-function
Directual JS-function
JS SDK step
JS SDK step
Lodash documentation
date formatting
understanding Date and Time in JavaScript
MomentJS documentation
https://regex101.com/
use MomentJS
Evaluating as JS expression
Example of using JS-expression in the step
Example of applying $D.concat in 'Edit object' scenario step
An example of 'Create object' step for creating a 'daily-unique' object
Edit object