JS SDK: Examples

Examples of Array Handling

Example 1: Finding Intersection of Arrays

In this example, we will match candidates (structured as 'Cand') with job offers (structured as 'Jobs') by considering the intersection of skills, represented as arrays such as finance, management, and programming. The candidate's skills are stored in 'cand_skills,' while the required skills (functions) for the job are stored in 'job_functions.' The matching result will be saved in the 'Job' object, specifically in the 'candidate_ids' field.

Here we use the following functions:

Content within the JS SDK Step:

// Scenario processes objects from Jobs

DirectualEngine.addEventListener(AppEvents.START, function(context){
  var candidates = $D.eval("{{candidates_ids}}")
  var functions = $D.eval("{{job_functions}}")
  var id = $D.eval("{{id}}")

  var matchCand = []
  
  if (candidates) {
  	candidates.split(",").forEach(function(cand) {
    	var candSkills = $D.store.get("Cand", cand, {fields: ["cand_skills"]});
       	if ($D.arrayContainsAny(candSkills, functions)) {
        	matchCand = $D.concat(matchCand,cand)
        }
    })
  }
  $D.store.save("Jobs", {"id": id, "candidate_ids": matchCand }, false)
  return true;
});

Example 2: Composing JSON with Custom Property Names

While the JSON step is useful, it doesn't support custom property names. Here's how to work around that limitation.

For instance, if you have structures for 'Authors' and 'Books' and want to compose JSON like this:

{
    "name": "Leo Tolstoy",
    "book1": {
        "id": "book1",
        "title": "War and Peace"
    },
    "book2": {
         "id": "book2",
         "title": "Anna Karenina"
     }
 }

We can do that with the following JS SDK code:

DirectualEngine.addEventListener(AppEvents.START, function(context){
  var id = $D.eval('{{id}}')
  var array = $D.eval('{{book_ids}}').split(',')
  var newObject = {}
  newObject.name = $D.eval('{{name}}')
  array && array.map(function(book) {
    newObject[book] = {}
    var bookObject = $D.store.get("Books", book, {fields: ["Title", "Year"]});
    for (var field in bookObject) {
    	newObject[book][field] = bookObject[field]
    }
  })
  //saving result object
  $D.store.save("WebUser", {"id": id, "json": JSON.stringify(newObject) }, false)
  return true
});

Last updated