借鑒:https://juejin.im/post/5cfcaa7ae51d45109b01b161#comment
這位大佬的處理方法很妙,但是我一眼看過去沒有明白,細細琢磨了下,終於明白了
1 const userList = [ 2 { 3 id: 1, 4 username: 'john', 5 sex: 1, 6 email: 'john@163.com' 7 }, 8 { 9 id: 2, 10 username: 'jerry', 11 sex: 1, 12 email: 'jerry@163.com' 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: 'john@163.com' }, 4 '2': { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' }, 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