1
0

More than 1 year has passed since last update.

JavaScriptの連想配列の要素を合計した配列を返す

Last updated at Posted at 2023-07-23

次のような連想配列を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();

それなりにシンプルに作れましたが、もっとよい方法があったらコメントください。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0