我如何在JXA中获得(地址ID包含addressId的人)?

时间:2019-03-20 16:21:46

标签: macos jxa javascript-automation

我在MacOS Mojave 10.14.3上使用带osascript的JavaScript来编写一个脚本,以显示联系人中的人员及其联系信息。我要添加一个功能来显示特定城市中的所有人。这是在脚本编辑器中运行的简化版本:

contacts = Application('Contacts').people;
matchingAddresses = contacts.addresses.whose({city: "San Diego"});

var addressIds = [];
for (var matchedAddress of matchingAddresses()) {
    if (matchedAddress.length > 0) {
        addressIds.push(matchedAddress[0].id());
    }
}

//loop contacts and get those with a matching address
var personIds = [];
for (var possiblePerson of contacts()) {
    for (var addressToCheck of possiblePerson.addresses()) {
        if (addressIds.includes(addressToCheck.id())) {
            var personId = possiblePerson.id();
            if (!personIds.includes(personId)) {
                personIds.push(personId);
            }
        }
    }
}

personIds.length;

我有一个效率更高的AppleScript测试版本。它不会遍历所有联系人,而是遍历匹配的地址并获得people whose id of addresses contains addressId

tell application "Contacts"
    set matchingAddresses to (every address where its city is "San Diego") of every person

    set personIds to {}
    repeat with matchedAddressList in matchingAddresses
        repeat with possibleAddress in items of contents of matchedAddressList
            set addressId to id of possibleAddress
            set matchingPerson to first item of (people whose id of addresses contains addressId)
            if not (personIds contains id of matchingPerson) then
                set end of personIds to id of matchingPerson
            end if
        end repeat
    end repeat

    count of personIds
end tell

AppleScript (people whose id of addresses contains addressId)总是返回一个人,因为地址ID是唯一的,因此只有一个人的地址列表可以包含任何特定的地址ID。

如果有更好的JavaScript或AppleScript方法可以按联系人所在城市之一的方式将其从“联系人”中引诱,

但是我的问题是,是否有一种方法可以使用JavaScript复制first item of (people whose id of addresses contains addressId)的功能,以便获得地址与该地址ID匹配的人?

1 个答案:

答案 0 :(得分:0)

也许更像是……

const contacts = Application('Contacts').people,
    matchingAddresses = contacts.addresses.whose({city: "San Diego"}),
    addressIds = matchingAddresses().filter(a=>a.length).map(a=>a[0].id());

addressIds[0]; // the first id

或者如果您想要地址...

const contacts = Application('Contacts').people,
    address = contacts.addresses.whose({city: "San Diego"})().filter(a=>a.length)[0]

address