请问这个小算法题怎么解?

请问这个小算法题怎么解?

let a = {

        'aa':[{

name:'zs',

num:10

},{

name:'lisi',

num:11

}],

'bb':[{

name:'zs',

num:12

},{

name:'lisi',

num:13

}],

'ccc':[{

name:'zs',

num:14

},{

name:'lisi',

num:15

},{

name:'ww',

num:16

}]

}

想要分别求求aa bb ccc 中的 num值相加的和


回答:

const a = {        

'aa':[

{name:'zs',num:10},

{name:'lisi',num:11}

],

'bb':[

{name:'zs',num:12},

{name:'lisi',num:13}

],

'cc':[

{name:'zs',num:14},

{name:'lisi',num:15}

],

}

const obj = {}

Object.keys(a).map((key)=>{

obj[key] = a[key].reduce((sum,item)=> (sum += item.num), 0)

})


回答:

Object.values(a).reduce((sum, arr) => arr.reduce((sum, item) => sum + item.num, sum), 0)总和

Object.entries(a).reduce((res, [k, v]) => (res[k] = v.reduce((sum, item) => sum + item.num, 0), res), {})分别求和

以上是 请问这个小算法题怎么解? 的全部内容, 来源链接: utcz.com/p/936395.html

回到顶部