/*
 * @Author: your name
 * @Date: 2021-08-13 17:17:06
 * @LastEditTime: 2021-08-25 10:49:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \md-\test\test.js
 */
// 雷姆提问,如何将两个数组中key值同样的项合并
const arr = [
    {key: 1, a: 'a'},
    {key: 1, b: 'b'},
    {key: 2, a: 'a'},
    {key: 2, b: 'b', c: 'c'},
    {key: 3, a: 'a', b: 'b'},
    {key: 4, a: 'a', b: 'b'},
]

const arr_res = [
    {key: 1, a: 'a', b: 'b'},
    {key: 2, a: 'a', b: 'b', c: 'c'},
    {key: 3, a: 'a', b: 'b'},
    {key: 4, a: 'a', b: 'b'},
]
// 湿鸡版本
var obj = arr.reduce((_,o)=>{
    _[o.key] ? (_[o.key] = Object.assign(_[o.key],o)) : (_[o.key] = o);return _;
},{})

var a = [];
for( var key in obj ){
    a.push(obj[key])
}

console.log(a);


// 晨晨版本
const map = new Map()
let crt
for (const item of arr) {
    crt = map.get(item.key)
    map.set(item.key, {...crt, ...item})
}
const res = [...map.values()]
console.log(res)

// 晨晨的一行版本
let x = arr.reduce((r, o) => ((r[o.key] = {...r[o.key], ...o}), r), []).filter(i => i)
console.log(x)

// 晨晨大佬一行版本修改
let x2 = arr.reduce((r,o)=>{
    // 通过解构进行合并不同的项
    r[o.key] = {...r[o.key], ...o}
    return r
},[])
// 因为key值不是百分百都对应数组的下标.所以用filter过滤
x2 = x2.filter(i=>i)
console.log(x2);