javascript多维数组按照key值合并的问题

              var arr = [{                    key: 1,                    name: 2,                    job: 3
                }, {                    key: 1,                    name: 22,                    job: 33
                }, {                    key: 2,                    name: 222,                    job: 333
                }, {                    key: 2,                    name: 2222,                    job: 3333
                }];

arr 这个数组有多个字段,我想根据key这个字段相同的属性的时候,就进行合并。
最终想实现的结果如arr2

    arr2 = [{                    key: 1,                    info: [{                        name: 2,                        job: 3
                    }, {                        name: 22,                        job: 33
                    }]
                }, {                    key: 2,                    info: [{                        name: 222,                        job: 333
                    }, {                        name: 2222,                        job: 3333
                    }]
                }];


皈依舞
浏览 1094回答 2
2回答

万千封印

var keys = Array.from(new Set(arr.map(o=>o.key)));var result = keys.map(key=>{    return {key: key,        info: arr.filter(o=>o.key==key).map(o=>({name:o.name, job:o.job}))     } });console.log(result);

牧羊人nacy

function mergeKey(arr) {  const keyMap = arr.reduce((r, item)=>{    const newItem = {...item};    delete newItem.key;     r[item.key] = (r[item.key] || []).concat(newItem);    return r;   }   , {});  return Object.keys(keyMap).map(key=>({     key,    info: keyMap[key],   })); } mergeKey(arr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript