Lodash mapping of nested collections

允我心安 提交于 2019-12-24 06:29:05

问题


I have following collection:

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'}]}
      ]
    }
  ]
}

And I am trying to extract collection of contracts. I tried using lodash 'map' function as follows: _.map(realty, 'entrances.units.contracts') but 'property' iterate does not work on arrays.

Any idea how can I extract collection of all contracts? Perhaps lodash chain could help but I am not sure how to use it :/.


回答1:


This seems to do the trick

_(realty.entrances).flatMap('units').flatMap('contracts').value()



回答2:


One posibility without lodash

var contractsArray = []

realty.entrances.forEach( e => {
 let units = e.units;
 units.forEach( u => contractsArray.push(u.contracts));
});



回答3:


If you want to get all contracts, using lodash:

_.map(realty.entrances, e => e.units.map(u => u.contracts));


来源:https://stackoverflow.com/questions/49553159/lodash-mapping-of-nested-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!