Get the value of a key/value list record by it's key
Dealing with record lists can be a valuable tool. Being able to refer to list items by key is more effective and intuitive than referencing items by their index in a list. Developers experienced with other languages that have better support for key/value lists quickly realize this limitation in applescript. Applescript does not have a built-in mechanism for identifying records by a string representation of their name, but a simple workaround can easily extract the value of a list record by a string representing it's key (name).
Usage...
The first example shows how to hard-code the retrieval of a key's value from a script variable with a known name. In this case we extract the value of the record pair named "asd" from the list stored in 'theRecordList' in the main script.
Code - Example 1...
set theRecordList to {qwe:1, rty:2, asd:3, fgh:4}
return (getRecordValue("asd")) --> returns: 3
to getRecordValue(theKey)
run script "on run{mainScript}
return mainScript's (" & theKey & " of theRecordList)
end" with parameters {me}
end getRecordValue
The second example is a modification of the first, which shows how to pass both the key name and the list to query to the handler. This way, the handler can be used to query multiple record lists, not just the one hard-coded list.
Code - Example 2...
set theRecordList to {qwe:1, rty:2, asd:3, fgh:4}
set theKey to "rty"
return (getRecordValue(theKey, theRecordList)) --> returns: 2
to getRecordValue(theKey, theList)
run script "on run{theKey,theList}
return (" & theKey & " of theList )
end" with parameters {theKey, theList}
end getRecordValue
Notes...
These are especially useful when trying to dynamically obtain a reference to a record list's item. For instance, if you were to replace the second line in example 2 above with "set theKey to choose from list {"qwe","rty","asd","fgh"}", the value returned from the choose from list command would be a string. But, to refer to a record, you must pass an actual variable as the reference, not a string representing it by name. Writing 'set theValue to "someKey" of someList' does not work as one might expect. Using the methods above, though, the references to the list items are constructed and compiled when the code executes, not when the main script is compiled. By writing it in string form and then running it as a script, you are allowed to pass a string as a reference to the variable, which when compiled is interpreted as a true variable... not as a string.
