Find a specific attribute value in a single line of code!

Automatically translated from English

Remember the days when you had to use nested loops and conditional statements to retrieve an object’s attribute? So you ended up with a long and complicated piece of code? Well, those days are over! Thanks to object notation combined with collections and their methods, you’re now able to write code faster, and in a more readable way!

Finding a specific attribute’s value has never been easier. Let’s take a look at a real life scenario and discover how!

Real life scenario

Imagine you want to filter your running processes by their type.

As you may already know, the Get process activity command allows you to retrieve a list of running processes and connected users. As shown below, part of the information returned is the process type:

{  
   {  
   "processes":[  
      {  
         "name":"Main",
         "sessionID":"",
         "number":0,
         "ID":0,
         "visible":false,
         "systemID":"140736073646912",
         "type":-39,  //Main 4D process
         "state":0,
         "cpuUsage":0.033,
         "cpuTime":922.62008,
         "preemptive":true
      },
     {  
         "name":"Application process",
         "sessionID":"",
         "number":1,
         "ID":13,
         "visible":true,
         "systemID":"123145536053248",
         "type":-1,  //Main process
         "state":2,
         "cpuUsage":0.002,
         "cpuTime":187.902836,
         "preemptive":false
      },
     {}
   ]
}


Let’s try to find the main process. If we did it the old way, we’d use a For loop with a conditional statement, which leaves us with quite a long piece of code:

C_OBJECT($obj)
C_LONGINT($i)
ARRAY OBJECT(processesCol;0)
$obj:
=Get process activity  
OB GET ARRAY
($obj;"processes";processesCol)
ARRAY OBJECT($result;0)
For ($i
;1;Size of array(processesCol))
 If
(OB Get(processesCol{$i};"type")= Main process)
  APPEND TO ARRAY($result;processesCol{$i})
 End if
End for

The old way works like a charm, but we have to admit it’s a bit long to write just to find a single element. Good news! Thanks to the query collection method, you can easily extract the value you want … in a single line of code!

C_COLLECTION($result)
$result:
=Get process activity.processes.query("type = :1";Main process)

And you’re done! Your code is clean, easy to understand and more readable. Long live simplicity!

We’ve just scratched the surface of what can be done. And of course, the query method supports more complex operations! In addition to querying a collection, you can also order, reduce, expand or filter them. More than 40 methods are available for an optimal use of collections!

A front-end developer with a sprinkle of Design Thinking.
Currently Product Marketing @4D