You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Lodash提取嵌套集合中合同数据的技术问询

Extract Nested Contracts from Realty Object Using 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 code
  • flatMap('units') iterates over each entrance, extracts its units array, and flattens the result
  • flatMap('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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:50:31