test.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * @Author: your name
  3. * @Date: 2021-08-13 17:17:06
  4. * @LastEditTime: 2021-08-25 10:49:48
  5. * @LastEditors: Please set LastEditors
  6. * @Description: In User Settings Edit
  7. * @FilePath: \md-\test\test.js
  8. */
  9. // 雷姆提问,如何将两个数组中key值同样的项合并
  10. const arr = [
  11. {key: 1, a: 'a'},
  12. {key: 1, b: 'b'},
  13. {key: 2, a: 'a'},
  14. {key: 2, b: 'b', c: 'c'},
  15. {key: 3, a: 'a', b: 'b'},
  16. {key: 4, a: 'a', b: 'b'},
  17. ]
  18. const arr_res = [
  19. {key: 1, a: 'a', b: 'b'},
  20. {key: 2, a: 'a', b: 'b', c: 'c'},
  21. {key: 3, a: 'a', b: 'b'},
  22. {key: 4, a: 'a', b: 'b'},
  23. ]
  24. // 湿鸡版本
  25. var obj = arr.reduce((_,o)=>{
  26. _[o.key] ? (_[o.key] = Object.assign(_[o.key],o)) : (_[o.key] = o);return _;
  27. },{})
  28. var a = [];
  29. for( var key in obj ){
  30. a.push(obj[key])
  31. }
  32. console.log(a);
  33. // 晨晨版本
  34. const map = new Map()
  35. let crt
  36. for (const item of arr) {
  37. crt = map.get(item.key)
  38. map.set(item.key, {...crt, ...item})
  39. }
  40. const res = [...map.values()]
  41. console.log(res)
  42. // 晨晨的一行版本
  43. let x = arr.reduce((r, o) => ((r[o.key] = {...r[o.key], ...o}), r), []).filter(i => i)
  44. console.log(x)
  45. // 晨晨大佬一行版本修改
  46. let x2 = arr.reduce((r,o)=>{
  47. // 通过解构进行合并不同的项
  48. r[o.key] = {...r[o.key], ...o}
  49. return r
  50. },[])
  51. // 因为key值不是百分百都对应数组的下标.所以用filter过滤
  52. x2 = x2.filter(i=>i)
  53. console.log(x2);