2 回答
TA贡献1895条经验 获得超7个赞
您可以使用数组归约方法,
let result = sample.reduce((prev, curr) => {
const descriptorName = curr.DESCRIPTOR;
const index = prev.findIndex((item) => item.DESCRIPTOR === descriptorName);
if(index > -1) {
prev[index].SCORE += curr.SCORE;
} else {
prev.push({'DESCRIPTOR': descriptorName, 'SCORE': curr.SCORE})
}
return prev;
}, []);
console.log(result);
TA贡献1825条经验 获得超4个赞
下面的代码根据 DESCRIPTOR_ID 对对象进行分组。首先使用方法遍历数组Array.prototype.reduce(),获取descriptor_id并将其作为key,并统计每个key的总分。最后使用方法获取值Object.values()。
const sample = [
{
DESCRIPTOR: 'HAPPY',
DESCRIPTOR_ID: 400001,
QUESTION_ID: 'A_QUES_1',
CHOICE: 'A',
SCORE: 1,
__v: 0,
},
{
DESCRIPTOR: 'HAPPY',
DESCRIPTOR_ID: 400001,
QUESTION_ID: 'A_QUES_2',
CHOICE: 'B',
SCORE: 2,
__v: 0,
},
{
DESCRIPTOR: 'SAD',
DESCRIPTOR_ID: 400002,
QUESTION_ID: 'B_QUES_1',
CHOICE: 'A',
SCORE: 2,
__v: 0,
},
{
DESCRIPTOR: 'SAD',
DESCRIPTOR_ID: 400002,
QUESTION_ID: 'B_QUES_2',
CHOICE: 'B',
SCORE: 2,
__v: 0,
},
];
const ret = Object.values(
sample.reduce((prev, c) => {
const p = prev;
const key = c.DESCRIPTOR_ID;
if (!p[key]) p[key] = { DESCRIPTOR: c.DESCRIPTOR, TOTAL_SCORE: c.SCORE };
else p[key].TOTAL_SCORE += c.SCORE;
return p;
}, {})
);
console.log(ret);
添加回答
举报