How to find a "script object" in a list?

I open several tabs in Chrome and then want to manipulate these tabs. To keep track of the tabs I use their id. To create the tabs I use this code:

repeat with theUrl in URLs
	set newTabElement to make new tab with properties {URL:theUrl}
	set myItem to my makeItem(theUrl, newTabElement)
	set end of itemList to myItem
end repeat

(URLs is a list or URLs.)

As you can see I create an object called myItem (definition below) that contains the URL and the tab. A tab in itself contains, among other things, an id. I then add this myItem to itemList.

myItem is defined like this:

on makeItem(myUrl, myTab)
	script theItem
		property theUrl : myUrl
		property theTabElement : myTabElement
	end script
	return theItem
end makeItem

So now I have a list itemList with multiple “script objects”. Next I want to search for the id of a tab with a certain URL. Can this be done without looping? Something like:

get id of theTabElement of theItem in itemList where URL of theItem is "https://macscripter.net"

or

get id of theTabElement of every item of itemList whose theUrl is "https://macscripter.net"

And is this a reasonable approach to my goal (to keep track of my tabs)?

No, you will have to loop. AppleScript doesn’t allow “whose” clauses on lists. I wish it did.

If you only have properties in your script object, its better to use records instead

repeat with theUrl in URLs
	set newTabElement to make new tab with properties {URL:theUrl}
	set end of itemList to my makeItem(theUrl, newTabElement)
end repeat

on makeItem(myUrl, myTab)
	return {theUrl:myUrl, theTabElement:myTab}
end makeItem

or you can do it directly without calling a subroutine

repeat with aUrl in URLs
	set newTabElement to make new tab with properties {URL:aUrl}
	set end of itemList to {theUrl:aUrl, theTabElement:newTabElement}
end repeat
1 Like

@robertfern has answered the OP’s question, and I thought I would write an ASObjC solution FWIW. This script creates a dictionary containing the URL of the opened tabs as the key and the ID of the opened tabs as the value. This is easily coerced to a record, or the tab ID of a particular URL can be gotten using valueForKey.

use framework "Foundation"
use scripting additions

set newURLs to {"https://www.macscripter.net/", "https://www.google.com/", "https://www.youtube.com/"}
set targetURL to "https://www.macscripter.net/"

set theURLs to {}
set theIDs to {}
tell application "Google Chrome" to tell window 1
	repeat with aUrl in newURLs
		make new tab with properties {URL:aUrl}
		set end of theURLs to URL of active tab
		set end of theIDs to id of active tab
	end repeat
end tell

-- create dictionary with URL as key and tab ID as value
set theDictionary to current application's NSDictionary's dictionaryWithObjects:theIDs forKeys:theURLs
-- coerce dictionary to record
set theRecord to theDictionary as record
-- get tab ID of target URL
set targetID to (theDictionary's valueForKey:targetURL) as text