Reputation: 1211
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 :/.
Upvotes: 4
Views: 7823
Reputation: 1056
If you want to get all contracts, using lodash:
_.map(realty.entrances, e => e.units.map(u => u.contracts));
Upvotes: 1
Reputation: 423
One posibility without lodash
var contractsArray = []
realty.entrances.forEach( e => {
let units = e.units;
units.forEach( u => contractsArray.push(u.contracts));
});
Upvotes: 0
Reputation: 214949
This seems to do the trick
_(realty.entrances).flatMap('units').flatMap('contracts').value()
Upvotes: 2