gpt4 book ai didi

javascript - 同级别对象的组数组

转载 作者:行者123 更新时间:2023-12-01 07:50:05 24 4
gpt4 key购买 nike

我有一个具有不同级别批准者的数组。我需要组合相似级别的对象并将它们与名称+计数器分组。

"APPROVERS": [
{
"LEVEL": "L5",
"EMAIL": "FTEST@TEST.COM",
"FULLNAME": "FNAME",
"POSITION": "FPOS",
"SLA": "48",
"STATUS": "INITIAL"
},
{
"LEVEL": "L4",
"EMAIL": "JTEST@TEST.COM",
"FULLNAME": "JNAME",
"POSITION": "JPOS",
"SLA": "48",
"STATUS": "INITIAL"
},
{
"LEVEL": "L5",
"EMAIL": "LTEST@TEST.COM",
"FULLNAME": "LNAME",
"POSITION": "GPOS",
"SLA": "48",
"STATUS": "INITIAL"
},
{
"LEVEL": "L5",
"EMAIL": "TTEST@TEST.COM",
"FULLNAME": "TNAME",
"POSITION": "CPOS",
"SLA": "48",
"STATUS": "INITIAL"
}
]

我需要将相同级别的对象合并为一个并提供唯一名称。
 "APPROVERS": [
{
"LEVEL": "L5",
"EMAIL1": "FTEST@TEST.COM",
"FULLNAME1": "FNAME",
"POSITION1": "FPOS",
"SLA1": "48",
"STATUS1": "INITIAL",
"EMAIL2": "LTEST@TEST.COM",
"FULLNAME2": "LNAME",
"POSITION2": "GPOS",
"SLA2": "48",
"STATUS2": "INITIAL",
"EMAIL3": "TTEST@TEST.COM",
"FULLNAME3": "TNAME",
"POSITION3": "CPOS",
"SLA3": "48",
"STATUS3": "INITIAL"
},
{
"LEVEL": "L4",
"EMAIL": "JTEST@TEST.COM",
"FULLNAME": "JNAME",
"POSITION": "JPOS",
"SLA": "48",
"STATUS": "INITIAL"
}
]

我只尝试通过循环数组来组合 EMAIL,但无法实现结果。请建议。
var result = [];
var i=0
APPROVERS.forEach(function(obj) {
var id = obj.LEVEL
if(!this[id]) result.push(this[id] = obj);
else this[id].EMAIL += obj.EMAIL+i;
i++;
}, Object.create(null));

console.log(result)

最佳答案

通过放置标签 lodash我想你不介意使用它。我不确定你是否理解它,但我已经尽力了 简洁性和可读性之间的平衡 .

function groupByLevel(approvers) {

const group = _.groupBy(approvers, 'LEVEL');
// console.log(group); // try logging to see what we have

return Object.entries(group).map( ([LEVEL, array]) => {

return array.reduce((acc, cur, idx) => ({
...acc,
['EMAIL' + (idx + 1)]: cur.EMAIL ,
['FULLNAME' + (idx + 1)]: cur.FULLNAME ,
['POSITION' + (idx + 1)]: cur.POSITION ,
['SLA' + (idx + 1)]: cur.SLA ,
['STATUS' + (idx + 1)]: cur.STATUS ,

}), { LEVEL });
})
}












var APPROVERS = [
{
LEVEL: 'L5',
EMAIL: 'FTEST@TEST.COM',
FULLNAME: 'FNAME',
POSITION: 'FPOS',
SLA: '48',
STATUS: 'INITIAL'
},
{
LEVEL: 'L4',
EMAIL: 'JTEST@TEST.COM',
FULLNAME: 'JNAME',
POSITION: 'JPOS',
SLA: '48',
STATUS: 'INITIAL'
},
{
LEVEL: 'L5',
EMAIL: 'LTEST@TEST.COM',
FULLNAME: 'LNAME',
POSITION: 'GPOS',
SLA: '48',
STATUS: 'INITIAL'
},
{
LEVEL: 'L5',
EMAIL: 'TTEST@TEST.COM',
FULLNAME: 'TNAME',
POSITION: 'CPOS',
SLA: '48',
STATUS: 'INITIAL'
}
]
console.log(groupByLevel(APPROVERS))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

关于javascript - 同级别对象的组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59435861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com