Skip to content

Reading values from dictionary in Javascript

I am trying to read tags from a selected collection of bibliographic data in ZOTERO with Javascript.

For those who aren’t familiar with ZOTERO: it has an in-built “run JS” panel to work directly with items selected / marked in the standalone version.

This is the script I am using to read data from a selected folder and access the tags:

var s = new Zotero.Search();
s.libraryID = ZoteroPane.getSelectedLibraryID();

var itemIDs = await s.search();

for (itemID of itemIDs) {
       item = Zotero.Items.get(itemID);
       return item;
       itemTAG = item.getTags();
       return itemTAG;
    }

When I call return itemIDs; before the for loop, I get 4943 key:value pairs, which correctly mirrors the number of items in my collection.

The structure looks like this:

[
    "0": 21848
    "1": 21849
    "2": 21850
    "3": 21851
    "4": 21852
    "5": 21853
    "6": 21854
    "7": 21855
    "8": 21856
    "9": 21857
    "10": 21858
]

What I would actually like to do is iterate through all IDs to get the bibliographic data for each item and return the tags.

This is why I first tried a for/in loop, but this didn’t work, supposedly because I wasn’t calling the key:value pairs (corresponding to a dictionary in Python?) correctly.

However, the above for/of loop works at least for the first item (item “0”) and returns the following data:

{
    "key": "BDSIJ5P4",
    "version": 1085,
    "itemType": "book",
    "place": "[Augsburg]",
    "publisher": "[Gabriel Bodenehr]",
    "date": "[circa 1730]",
    "title": "Constantinopel",
    "numPages": "1 Karte",
    "creators": [
        {
            "firstName": "Gabriel",
            "lastName": "Bodenehr",
            "creatorType": "author"
        }
    ],
    "tags": [
        {
            "tag": "Europa"
        }
    ],
    "collections": [
        "DUW2PJDP"
    ],
    "relations": {
        "dc:replaces": [
            "http://zotero.org/groups/2289797/items/ZB5J5VZK"
        ]
    },
    "dateAdded": "2019-02-13T17:27:29Z",
    "dateModified": "2020-03-23T13:13:13Z"
}

So my two questions are:

  1. How can I create a proper for/in loop that retrieves these same data for each item?
  2. How can I return tags only? It seems that item.getTags() [which I used in analogy to the getNotes() examples in the documentation] may not be a valid function. Would that be specific to Zotero or Javascript in general?

Answer

Use map() to call a function on every array element and return an array of all the results.

return itemIDs.map(itemID => Zotero.Items.get(itemID).getTags())