js reduce数组转对象

借鉴:https://juejin.im/post/5cfcaa7ae51d45109b01b161#comment
这位大佬的处理方法很妙,但是我一眼看过去没有明白,细细琢磨了下,终于明白了

 1 const userList = [
 2     {
 3       id: 1,
 4       username: 'john',
 5       sex: 1,
 6       email: '[email protected]'
 7     },
 8     {
 9       id: 2,
10       username: 'jerry',
11       sex: 1,
12       email: '[email protected]'
13     },
14     {
15       id: 3,
16       username: 'nancy',
17       sex: 0,
18       email: ''
19     }
20   ];
21 
22 const userObj = userList.reduce((acc, person) => {
23     return {...acc, [person.id]: person}
24 }, {})
25 
26 console.log(userObj)
1 // 结果
2 {
3   '1': { id: 1, username: 'john', sex: 1, email: '[email protected]' },
4   '2': { id: 2, username: 'jerry', sex: 1, email: '[email protected]' },
5   '3': { id: 3, username: 'nancy', sex: 0, email: '' }
6 }

结合官方文档一起服用,效果更佳https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

解读: 

acc是累机器,person是当前值,{}是初始值

{}累加数组里面的每一项,根据id为key,数组里的每一项为value

...acc是对象的解构赋值,数组里的每一项对象都会被解构赋值拷贝到新的对象上

注意品味[person.id]: person是变量的解构赋值,从当前对象person中提取id

猜你喜欢

转载自www.cnblogs.com/caoshufang/p/12149987.html