次のような連想配列を1つの配列にまとめ、キーごとに要素をまとめたい場合にどうすればいいのか、少し悩んだのでその方法を残しておきます。
////////////////////////
// Before
////////////////////////
facet: {
apple: {
'1': 10,
'2': 20
},
orange: {
'1': 30,
'2': 40,
'3': 50
}
}
////////////////////////
// After
////////////////////////
[
{
'id': '1',
'sum': 40 // 10+30
},
{
'id': '2',
'sum': 60 // 20+40
},
{
'id': '3',
'sum': 50 // 50
}
]
今回は JavaScript
で実現するので、何かと便利な lodash
を使います。
_.transform(..)
を使うことで連想配列を配列に変換し、内部でキーの比較を行っています。
_.chain(facet)
.transform((result, value) => {
_.forEach(value, (v, k) => {
if (result[k]) {
result[k].sum += v;
} else {
result[k] = {
id: k,
sum: v ? v : 0
};
}
});
})
.sortBy([ 'id' ])
.value();
それなりにシンプルに作れましたが、もっとよい方法があったらコメントください。