基于Lodash提取嵌套集合中合同数据的技术问询
Hey there! Extracting those nested contracts from your realty structure with Lodash is totally straightforward. Here are a few practical, clean approaches to get all contract objects into a single array:
Approach 1: Chained flatMap Calls
This method is explicit and easy to follow, breaking down the nested extraction step by step:
const _ = require('lodash'); var realty = { name: 'Realty A', entrances: [ { name: 'Entrance A', units: [ {name: 'unitA', contracts: [{contractNo: 'no.963'}, {contractNo: 'no.741'}]}, {name: 'unitB', contracts: [{contractNo: 'no.789'}, {contractNo: 'no.564'}]} ] }, { name: 'Entrance B', units: [ {name: 'unitC', contracts: [{contractNo: 'no.419'}, {contractNo: 'no.748'}]}, {name: 'unitD', contracts: [{contractNo: 'no.951'}, {contractNo: 'no.357'}]} ] } ] }; const contracts = _.chain(realty.entrances) .flatMap('units') // Pull all units from every entrance, flatten into one array .flatMap('contracts') // Pull all contracts from every unit, flatten into the final array .value();
_.chain()enables Lodash method chaining for cleaner, more readable codeflatMap('units')iterates over each entrance, extracts itsunitsarray, and flattens the resultflatMap('contracts')repeats the process for units to collect all nested contracts
Approach 2: flatMapDeep for Recursive Flattening
If you anticipate deeper nesting in the future, flatMapDeep handles recursive flattening automatically:
const contracts = _.flatMapDeep(realty.entrances, entrance => entrance.units.map(unit => unit.contracts) );
Or a more concise one-liner:
const contracts = _.flatMapDeep(realty.entrances, e => e.units.map(u => u.contracts));
This method recursively flattens all layers of nested arrays, making it flexible for evolving data structures.
Approach 3: Nested flatMap Calls (No Chaining)
If you prefer avoiding method chaining, you can nest flatMap calls directly:
const contracts = _.flatMap(_.flatMap(realty.entrances, 'units'), 'contracts');
This achieves the exact same result as the chained approach, just in a more compact, non-chained format.
Expected Output
All three methods will return this array of contract objects:
[ { contractNo: 'no.963' }, { contractNo: 'no.741' }, { contractNo: 'no.789' }, { contractNo: 'no.564' }, { contractNo: 'no.419' }, { contractNo: 'no.748' }, { contractNo: 'no.951' }, { contractNo: 'no.357' } ]
内容的提问来源于stack exchange,提问作者Jan Tajovsky

