I have a list of records and I would like to get the value of one of the records items. The problem is that I only have the name of the property that I want to access as a string, so somehow I need to convert the string into a property like so:
set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}
set propertyVar to "SKU1"
set myVar to propertyVar of myRecords
I found some code that would convert 2 strings into a record:
set string1 to "SKU1"
set string2 to "7"
set myRecord to (run script ("return {|" & string1 & "|:\"" & string2 as string) & "\"}")
return SKU1 of myRecord
I just figure out how to convert a string into a property without also setting its value.
the easiest way nowadays is to use AppleScriptObjC
use framework "Foundation"
set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}
set cocoaRecords to current application's NSDictionary's dictionaryWithDictionary:myRecords
set propertyVar to "SKU1"
set myVar to (cocoaRecords's objectForKey:propertyVar) as text
set myRecords to {SKU1:"7", SKU2:"9", SKU3:"4"}
set p to "SKU1"
set theScript to "on run argv
return " & p & " of item 1 of argv
end"
run script theScript with parameters {myRecords}
That’s correct. We’re making use of eval which is compiling and executing generated code (executing arbitrary code). It’s considered harmful in professional programming but we’re talking AppleScript so it’s fine
What it basically does is generate the following code for compilation and execution:
But what if you use that key multiple times? The power of record access in vanilla AppleScript is 100+ times faster and efficient than in ASObjC. So these kind of discussions are somewhat useless because there are many situations where the overhead of “slow second level evaluation” will become minor and the cumbersomeness of the bridge will become a problem.