jq Cheat Sheet/Reduce array into object map

Build an object keyed by a field.

Section: Variables, Reduce, and Advanced Transformations

Reduce array into object map

bash
bash
echo '[{"id":1,"name":"a"},{"id":2,"name":"b"}]' | jq 'reduce .[] as $item ({}; .[$item.id|tostring] = $item.name)'
Explanation

This pattern is common when converting lists into keyed lookup tables.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Variables, Reduce, and Advanced Transformations
Reduce array to sum
Aggregate values manually with `reduce`.
OpenIn sheetbashsame section
Transform object entries
Update every key-value pair in an object.
OpenIn sheetbashsame section
Convert object to entries array
Represent an object as key-value entry objects.
OpenIn sheetbashsame section
Convert entries back to object
Turn key-value entry objects into a normal object.
OpenIn sheetbashsame section
Capture value into variable
Store a subexpression and reuse it later.
OpenIn sheetbashsame section
Recursively transform all strings
Walk the document and mutate matching values.
OpenIn sheetbashsame section