Map、Filter、Reduceなどの高次関数を使いたかったのです。
私の問題は整理されていない配列があるため、私が望む結果を得るためにループ操作を実行しなければならなかったことです。配列には_id
とtotalCount
の2つのフィールドがあり、配列は長さが最小0から3になります。
totalCount
各反復は2つのフィールドで構成されます.1つはorderstatusで、もう1つは合計です。else if else if normal orderstatusは "Merchant"または "driver"または "user"です。その反復合計を受け取り、MerchantCount
のような配列に格納したいと思います。2つのループの代わりに高次関数を使用する
これは私のコードです:
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
}
]
}
]
ループが行っております:
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;
}
}
}
を結果はおおよそ以下のようになります。
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, …}
私は同じ操作になりたいですMap/FilterまたはReduceメソッドを使用して実行されます。
なぜ 'map' /' reduce'を使ってみたいのですが、あなたのコードをどのように改善すると思いますか? – Bergi
@Bergiコードを改善するかどうかは分かりません。これで高次関数を試してみただけです – Kannan
コードには副作用があります(既存のオブジェクトにフィールドを追加する)。 'for ... of'ループを使って単純化することもできますし、NinaScholzの答えのように' if'カスケードの代わりに動的プロパティ名を使うこともできます。 – Bergi