I was searching high and low for two days for any way to audit all my YAML keys/fields in my vault and couldn’t find anything, so I went ahead and coded it myself. My implementation is simple, but I’ll probably use it as a launching point for other projects (and I’m hoping somebody else finds it useful, too!).
I keep one note with this query for reference so I can spot-check whether I have any keys or fields misspelled, capitalized differently, etc., since I hate to think something might get lost from my queries due to a typo. It’s both a blessing and a curse that you can put whatever you want in there!
I believe that, as long as you have the same versions of Obsidian (v0.14.15) and the Obsidian Dataview plugin (v0.5.36) installed that I do, you should literally be able to copy/paste this into a DataviewJS codeblock and it should just work for you…?
// Unique YAML Keys Audit
// Brought to you by Jocelyn Tuohy
// 2022.06.19
// Created using:
// - Obsidian (v0.14.15)
// - the Obsidian Dataview plugin (v0.5.36)
let uniqueKeyArray = [];
for (let file of dv.pages().file){
for (let key of Object.keys(file.frontmatter)){
// Check whether we've already captured this key in our array
let i = null;
i = uniqueKeyArray.findIndex((k) => k.fieldName === key);
// If we haven't encountered this key before, push an
// object with its key and intialized count to the array
if (i === -1){
i = uniqueKeyArray.push({fieldName: key, count: 0}) - 1;
}
// increase the running count for this unique key
uniqueKeyArray[i].count++;
}
}
// Create a table with "Unique Key" and "Key Count" headers from
// the array, sorting first alphabetically (ascending) then by
// count (descending). This puts keys with only capitalization
// differences together (at least in US English) so we can quickly
// see which version is more common.
dv.table(["Unique Key", "Key Count"], uniqueKeyArray
.sort((a, b) =>
a.fieldName.localeCompare(b.fieldName) || b.count - a.count)
.map(k => [k.fieldName, k.count]));
As written, this will count every instance of a YAML field, even if it’s used multiple times in the same file.
I might eventually display the file names of anomalies in place of their “1” counts, but it’s pretty straightforward to search for a YAML field name once I know it exists, so I’m not rushing to do it. If you need that implementation but are new to coding and could use some help, let me know and maybe it will jump up my to-do list! My own coding skills are a teensy bit rusty, plus I started working with DataviewJS only yesterday, so if you have any suggestions or corrections I’d love to hear from you.