Find Record with List by key in AppleScript
Is there way to get a Record by the value of one of its keys without looping?
I've been doing this:
set theKey to 22
set theRecords to {{key:11, value:"foo"}, {key:22, value:"bar"}}
repeat with theRecord in theRecords
if key of theRecord = theKey then
display dialog (key of theRecord as text) & ":" & value of theRecord
end if
end repeat
Solution 1:
I suppose that you are worried about the speed of iterating. Iterating would be a time of order-n O(n).
In AppleScript, you can possibly use a record of records instead of a list of records, but I believe that then the class of the key would have to be an identifier -- not integer like in your example.
Here is a link to somebody with a similar question: Emulating associative arrays in AppleScript
Lauri Ranta's answer is to use the command-line tool called "awk".
The solution that I toyed with was to make a faceless background app that would be what is called an "Agent" which AppleScript's could call upon for using its datastructures such as an associative array (also known as a dictionary or a Mapping.)
I didn't get my solution done. It's just an idea, but you could use Lauri's answer, she usually knows what she's talking about.
Since I know a little Pyton, and since Pyton comes with OS X, pre-installed in the System Folder, I would consider using Python myself.
I tried it again in "pure AppleScript" with the following code which I'm not really happy with:
set theRecords to {fooKey:{key:"fooKey", value:"fooValue"}, barKey:{key:"barKey", value:"barValue"}}
try
set theRecord to get barKey of theRecords
display dialog (key of theRecord & ":" & value of theRecord)
on error errorMessage number errorNumber
if errorNumber is not equal to -128 then
display dialog "No match"
end if
end try
You can mix shell script and AppleScripts:
-- in AppleScript, you can call a shell script
do shell script "<enter your shell script here>"
Or, you can call an AppleScript from a shell script with the command-line tool called "osascript".