Ich wollte Funktionen höherer Ordnung wie Map, Filter, Reduce verwenden.
Mein Problem ist, ich habe ein Array, das nicht organisiert ist, also musste ich eine Schleife durchführen, um das gewünschte Ergebnis zu erhalten. Ein Array hat zwei Felder eins ist _id
und totalCount
Das ist ein Array die Länge wird mindestens 0 bis 3.
Die totalCount
jede Iteration besteht aus zwei Feldern ist ein Orderstatus und ein anderes ist insgesamt Ich möchte eine normale wenn sonst Bedingung wenn ich orderstatus ist "Merchant" oder "driver" oder "user" Ich möchte diese iterierte Summe nehmen und in meinem Array wie MerchantCount
speichern.Verwenden von Funktionen höherer Ordnung anstelle von zwei Schleifen
Dies ist mein Code:
var arr = [{
_id: "2017-12-08",
totalcount: [{
orderstatus: "MERCHANT",
total: 1
}]
},
{
_id: "2017-12-02",
totalcount: [{
orderstatus: "USER",
total: 2
}]
},
{
_id: "2017-12-06",
totalcount: [{
orderstatus: "DRIVER",
total: 1
}]
},
{
_id: "2017-12-07",
totalcount: [{
orderstatus: "MERCHANT",
total: 3
}]
},
{
_id: "2017-12-04",
totalcount: [{
orderstatus: "DRIVER",
total: 1
},
{
orderstatus: "MERCHANT",
total: 2
},
{
orderstatus: "USER",
total: 1
}
]
}
]
Die Schleife Durchführung am:
for (let i = 0; i < recentUserCount.length; i++) {
for (let j = 0; j < recentUserCount[i].totalcount.length; j++) {
if (recentUserCount[i].totalcount[j].usertype == "DRIVER") {
recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total;
} else if (recentUserCount[i].totalcount[j].usertype == "USER") {
recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total;
} else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") {
recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total;
}
}
}
Das Ergebnis etwa wie unten sein wird:
0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"}
1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"}
2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"}
3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …}
ich die gleiche Operation sein wollen durchgeführt mit Map/Filter oder Reduce-Methode.
Warum genau wollen Sie 'map' /' reduce' verwenden, wie würden Sie Ihren Code verbessern? – Bergi
@Bergi Ich weiß nicht, ob es meinen Code verbessern wird oder nicht bro wollte einfach nur Funktionen höherer Ordnung mit diesem so – Kannan
Ich werde nicht wirklich, wie Ihr Code hat eine Nebenwirkung (Hinzufügen von Feldern zu den vorhandenen Objekten). Sie können es jedoch vereinfachen, indem Sie "for ... of" -Schleifen verwenden und dynamische Eigenschaftsnamen anstelle dieser "if" -Kaskade verwenden, wie in NinaScholz 'Antwort. – Bergi