JavaScript
Map and flatten records with flatMap
Use flatMap when one input entry should produce zero, one, or several output entries. Return an empty array to omit an entry and a short array to expand it.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const rows = [{name: "A", tags: ["red", "blue"]}, {name: "B", tags: []}];
const tags = rows.flatMap(row => row.tags.map(tag => `${row.name}:${tag}`));
console.log(JSON.stringify(tags));How it works
The inner map labels each tag with its source row. FlatMap then removes one array level from those results. The empty tags array on row B contributes no output. This combines an expansion and a flattening pass into a readable operation.
Limits and mistakes
FlatMap flattens only one level and does not await asynchronous callbacks. For async work, collect promises, await them, and flatten the resolved arrays. Large expansions can still allocate a very large output array.
Check the result
Expect ["A:red","A:blue"]. Add a second tagged row to confirm order: input row order is preserved, followed by each row’s tag order.
Sources
Reference documentation for the behavior used in this guide: