item to actors script

I have this macro for updating actors in a compendium with spells from a compendium of spells (i.e. replacing by name any spells on the actors, so I can push my improvements to spell automation onto the monsters in my compendium). It works, but I'm wondering if I can make it more efficient - currently, it's doing an individual update per actor, and that feels like it should be possible to batch into a single update (which would also allow me to construct the update list by getting an extended index with the items for the monsters, and not have to getDocument on each monster). There's definitely a bunch of smaller improvements that can be made as well - this is slightly sketchy code and I'm out of practice.

let pack = game.packs.get("DDBImports.spells")
let index = pack.index
let monsterpack = game.packs.get("DDBImports.monsters")
//await monsterpack.getIndex({fields:["items"]}) 
let monsterindex = Array.from(monsterpack.index)
for (let monster of monsterindex){
    console.log(monster.name)
    let act = await monsterpack.getDocument(monster._id)
    let items = Array.from(act.items)
    let updates = []
    for (let item of items){
        if(item.type !== "spell") continue //only replacing spells
        let newitem = await pack.getDocument(index.find(i => i.name === item.name)?._id) //find a spell with the same name
        if(!newitem) continue //if none, then skip to next
        let update = duplicate(newitem.data)
        update.data.preparation = item.data.data.preparation;
        update.data.uses = item.data.data.uses
        update.data.consume = item.data.data.consume
        update._id = item.data._id
        updates.push(update)
    }
    if(!updates) continue
    console.log(updates)
    await act.updateEmbeddedDocuments("Item", updates)
}
Was this page helpful?