Variables & functions

Example expression:

.sections[].entries[]? | select(.title | ascii_downcase | contains("reduce"))

Finds the jq documentation where the title contains "reduce". It's a bit unwieldy to tinker with, so we can change this to a function.

In JavaScript this would be:

function findEntry(string) {
  const result = [];
  manual.sections.forEach(section => {
    if (section.entries) {
      section.entries.forEach(entry => {
        if (entry.title.toLowerCase().includes(string)) {
          result.push(entry);
        }
      });
    }
  });

  return result
}

In jq to make a function, we use the def keyword:

def findEntry(string):
  .sections[]
  .entries[]? |
    select(
      .title |
      ascii_downcase |
      contains(string)
    )
  ;

The ending semi-colon ; is important (unlike JavaScript!) as it tells jq that the function has finished. Now in my expression I can call findEntry and it will search for me:

def findEntry(string):
  .sections[]
  .entries[]? |
    select(
      .title |
      ascii_downcase |
      contains(string)
    )
  ;

findEntry("reduce")