基于子数组实现数组扁平化的优雅方案咨询
Absolutely! You can absolutely achieve this cleanly with popular JavaScript utility libraries—no need to write messy nested loops from scratch. Here are a few elegant approaches using widely-used tools:
Using Lodash
Lodash's flatMap is perfect here because it combines mapping and flattening into a single step. It iterates over each batch, maps each file to your desired object shape, then automatically flattens the resulting array of arrays:
const _ = require('lodash'); const originalData = [ {batchId: 123, files: [{fileName: 'fileA.txt'}, {fileName: 'fileB.txt'}]}, {batchId: 456, files: [{fileName: 'fileC.txt'}, {fileName: 'fileD.txt'}]} ]; const flattened = _.flatMap(originalData, batch => batch.files.map(file => ({batchId: batch.batchId, fileName: file.fileName})) ); console.log(flattened); // Output: [{batchId:123, fileName:'fileA.txt'}, {batchId:123, fileName:'fileB.txt'}, {batchId:456, fileName:'fileC.txt'}, {batchId:456, fileName:'fileD.txt'}]
Using Ramda
If you prefer a functional programming approach, Ramda's chain function does the same job as Lodash's flatMap (since chain is the functional equivalent of flatMap). It composes the mapping and flattening operations neatly:
const R = require('ramda'); const originalData = [/* same as above */]; const flattenBatches = R.chain(batch => R.map(file => ({batchId: batch.batchId, fileName: file.fileName}), batch.files) ); const flattened = flattenBatches(originalData);
Bonus: Vanilla JavaScript (No Libraries)
While you asked for toolkits, it's worth noting modern vanilla JS has a built-in flatMap method that does exactly what you need—no external libraries required:
const originalData = [/* same as above */]; const flattened = originalData.flatMap(batch => batch.files.map(file => ({batchId: batch.batchId, fileName: file.fileName})) );
All these approaches give you exactly the flattened structure you need, and they’re far more readable than writing manual loops or reduce operations. Pick the one that fits your project’s existing tooling!
内容的提问来源于stack exchange,提问作者Gatmando

