0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jsでオブジェクト特定値の合計を一行で出す

Last updated at Posted at 2021-02-03

次のようなオブジェクトの特定の値(num)の合計だけを
出すのにmapやeach文でゴニョゴニョ数行書くのやだなぁと思い、


ex = {
  id: 1,
  childrens: [
    {id: 1, num: 1},
    {id: 2, num: 3}
  ]
}

そうだreduceがあると思ったのですが、
シンプルな配列と違って、ちょっと扱いに迷ったので簡単にメモ。

ex.childrens.reduce((sum, obj) =>{return sum + obj.num}, 0);

※0は、初期値。省略すると配列[0]の値。

ちなみに、オブジェクトのオブジェクトの場合、Object.valuesを使ってArray化して利用するアイデアも。

ex2 = {
  0: {id: 1, num: 1},
  1: {id: 2, num: 3}
}
Object.values(ex2).reduce((sum, obj) =>{return sum + obj.num}, 0);

公式:
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

参考:
https://stackoverflow.com/questions/15748656/javascript-reduce-on-object

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?