Skip to content

Instantly share code, notes, and snippets.

@zuphilip
Last active April 12, 2020 10:09
Show Gist options
  • Save zuphilip/197547bc644cc4e0a57c3242af53e90b to your computer and use it in GitHub Desktop.
Save zuphilip/197547bc644cc4e0a57c3242af53e90b to your computer and use it in GitHub Desktop.
Update metadata by ISBN lookup from LoC
// can be run within Zotero "Run Javascript" tool
var overwrite = true;
var skip = ["key", "dateAdded"];
var updated = [];
var items = Zotero.getActiveZoteroPane().getSelectedItems();
let translate = new Zotero.Translate["Search"]();
// LoC ISBN translator:
translate.setTranslator("c070e5a2-4bfd-44bb-9b3c-4be20c50d0d9");
function lookupISBN(isbn) {
translate.setSearch({ISBN: isbn});
return translate.translate();
}
for (let item of items) {
let isbn = item.getField("ISBN");
if (!isbn) continue;
let lookupItem = await lookupISBN(isbn);
// going through the simple fields
for (let key in lookupItem[0].toJSON()) {
let value = lookupItem[0].getField(key);
if (value && !skip.includes(key)) {
let oldValue = item.getField(key);
// only set value if empty or overwrite is forced
if (!oldValue || overwrite) {
item.setField(key, value);
updated.push(key);
}
}
}
// creators
if (lookupItem[0].getCreators()) {
if (item.getCreators().length == 0 || overwrite) {
item.setCreators(lookupItem[0].getCreators());
updated.push("creators");
}
}
// tags
if (lookupItem[0].getTags()) {
if (item.getTags().length == 0 || overwrite) {
item.setTags(lookupItem[0].getTags());
updated.push("tags");
}
}
// notes
let noteIDs = lookupItem[0].getNotes();
if (noteIDs.length > 0 && (item.getNotes().length == 0 || overwrite)) {
for (let id of noteIDs) {
let note = Zotero.Items.get(id);
// link note id to item and save it
note.parentID = item.id;
note.saveTx();
updated.push("notes");
}
}
var itemID = item.saveTx();
}
return updated;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment