test.js 891 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // 雷姆提问,如何将两个数组中key值同样的项合并
  2. const arr = [
  3. {key: 1, a: 'a'},
  4. {key: 1, b: 'b'},
  5. {key: 2, a: 'a'},
  6. {key: 2, b: 'b', c: 'c'},
  7. {key: 3, a: 'a', b: 'b'},
  8. {key: 4, a: 'a', b: 'b'},
  9. ]
  10. const arr_res = [
  11. {key: 1, a: 'a', b: 'b'},
  12. {key: 2, a: 'a', b: 'b', c: 'c'},
  13. {key: 3, a: 'a', b: 'b'},
  14. {key: 4, a: 'a', b: 'b'},
  15. ]
  16. // 湿鸡版本
  17. var obj = arr.reduce((_,o)=>{
  18. _[o.key] ? (_[o.key] = Object.assign(_[o.key],o)) : (_[o.key] = o);return _;
  19. },{})
  20. var a = [];
  21. for( var key in obj ){
  22. a.push(obj[key])
  23. }
  24. console.log(a);
  25. // 晨晨版本
  26. const map = new Map()
  27. let crt
  28. for (const item of arr) {
  29. crt = map.get(item.key)
  30. map.set(item.key, {...crt, ...item})
  31. }
  32. const res = [...map.values()]
  33. console.log(res)
  34. // 晨晨的一行版本
  35. arr.reduce((r, o) => ((r[o.key] = {...r[o.key], ...o}), r), []).filter(i => i)