Ich habe folgende Sammlung:
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"}]}
]
}
]
}
Und ich versuche, die Sammlung von Verträgen zu extrahieren. Ich habe versucht, lodash "map" -Funktion wie folgt zu verwenden:
_.map(realty, "entrances.units.contracts")
aber "property" iterate funktioniert nicht auf Arrays.
Irgendeine Idee, wie kann ich Sammlung aller Verträge extrahieren? Vielleicht könnte lodash Kette helfen, aber ich bin nicht sicher, wie man es benutzt: /.
Antworten:
1 für die Antwort № 1Dies scheint den Trick zu machen
_(realty.entrances).flatMap("units").flatMap("contracts").value()
0 für die Antwort № 2
Eine Möglichkeit ohne lodash
var contractsArray = []
realty.entrances.forEach( e => {
let units = e.units;
units.forEach( u => contractsArray.push(u.contracts));
});
0 für die Antwort № 3
Wenn Sie alle Verträge erhalten möchten, verwenden Sie lodash:
_.map(realty.entrances, e => e.units.map(u => u.contracts));