简单版:
const arr = [
{
key: 'aaa',
tableName: 'bbbbb'
},
{
key: 'aaa',
tableName: 'bbbbb'
},{
key: 'www',
tableName: 'bbbbb'
},
{
key: 'www',
tableName: 'bbbbb'
},
{
key: 'mysql_ytr',
tableName: 'bbbbb'
}
]
// 把arr按key進行分組, 輸出結果是對象,對象裡面用key做鍵名,值是數組
const result = {};
arr.forEach(item => {
if (!result[item.key]) {
result[item.key] = [];
}
result[item.key].push(item);
});
console.log(result);
最终效果
复杂版----------------------:
const keyObj = {
1: {
key: 'sensitive',
msg: '敏感信息'
},
2:{
key: 'noExist',
msg: '不存在'
},
3:{
key: 'connectFailed',
msg: '連接失敗'
},
}
const arr = [
{
databaseName: 'aaaa',
failedType: 3,
tableName: 'bbbbb'
},
{
databaseName: 'kkkk',
failedType: 1,
tableName: 'bbbbb'
},{
databaseName: 'wwwww',
failedType: 2,
tableName: 'bbbbb'
},
{
databaseName: 'wwwww',
failedType: 2,
tableName: 'bbbbb'
}
]
// 把arr按failedType進行分組, 輸出結果是數組,數組裡面是按failedType對應keyObj里面的key做鍵名分好的數組
const result = {};
arr.forEach(item => {
const key = keyObj[item.failedType].key;
const msg = keyObj[item.failedType].msg;
if (!result[key]) {
result[key] = {
msg: msg,
data: []
};
}
result[key].data.push(item);
});
console.log(result);
最终效果: