'Getting table name from cell selection in Apple Numbers using Javascript for Automation (JXA)

I'm trying to convert this Applescript to Javascript for Automation.

Is there anyone who can help to write the line bellow in Javascript for Automation?

set thisTable to the first table whose class of selection range is range

Appreciate any help!



Solution 1:[1]

This will require the use of a whose clause for querying the element array of tables in the selected sheet—essentially, you want to find all Table objects whose selectionRange attribute is not null (which is analogous to asserting that its class is range). Unfortunately, there seems to be a bug in JXA that prevents comparisons with null. So while it would be optimal to simply check _not: [{ selectionRange: null }] in the code below, I found that that approach did not work. Instead, the following appears (albeit not particularly elegantly) to do what you're looking for:

Numbers = Application('Numbers')

selectedTables = Numbers.documents[0].activeSheet.tables.whose({
    _not: [{
        _match: [ObjectSpecifier().selectionRange.name, '']
    }]
})

if (selectedTables.length > 0) {
    thisTable = selectedTables[0]
} else {
    // No table is selected -- handle accordingly
}

This is a pretty hacky approach (it relies on the fact that selectionRange.name isn't even a valid key for non-selected tables), but given the buggy state of JXA, it may be the best one can do.

Further Reading:

Solution 2:[2]

Another way ... selected table and selection range

const app = Application("Numbers"),
      doc = app.documents[0],
      sheet= doc.activeSheet,
      tbls = sheet.tables;

let seltable = tbls[tbls.selectionRange().findIndex(el => !!el)];

let selrange = seltable.selectionRange;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aaplmath
Solution 2 SGIII