javascript - 计算数组中答案的冗余
问题描述
我有一个像这样的对象数组
[
{_id: "5ca8b8ca0f1b2f54646ded9a", question: "Do you like it?", answer: "yes"},
{_id: "5ca8b8ca0f1b2f54646ded99", question: "Do you like it?", answer: "no"},
{_id: "5ca8b8f80f1b2f54646deda1", question: "Where are you?", answer: "home"},
{_id: "5ca8b8f80f1b2f54646deda0", question: "Where are you?", answer: "home"}
]
我希望它被复制如下:
[
{
"question": "Do you like it?",
"answers": [{"answer": "yes", "count": 1}, {"answer": "no", "count": 1}]
},
{
"question": "Where are you?",
"answers": [{"answer": "home", "count": 2}]
}
]
我试图解决这个问题,但我不能,所以任何帮助将不胜感激。谢谢
解决方案
如果该对不存在,我们可以使用它Array.find
来查找问答对,然后添加一个新的问答对对象,或者更新现有的问答对对象。
如果问题存在但答案不存在,则只需在answers
数组中添加新答案。
如果问题和答案都存在,则将 answercount
属性增加 1。
如果问题本身缺失,则添加一个具有question
属性和answers
属性的新对象并将其设置count
为1
.
然后最后使用Array.reduce
将对象累积到一个数组中。
const data = [
{_id: "5ca8b8ca0f1b2f54646ded9a", question: "Do you like it ?", answer: "yes"},
{_id: "5ca8b8ca0f1b2f54646ded99", question: "Do you like it ?", answer: "no"},
{_id: "5ca8b8f80f1b2f54646deda1", question: "Where are you ?", answer: "home"},
{_id: "5ca8b8f80f1b2f54646deda0", question: "Where are you ?", answer: "home"}
];
const res = data.reduce((acc, {question, answer}) => {
qFound = acc.find(qa => qa.question === question);
if(qFound){
ansFound = qFound.answers.find(ans => ans.answer === answer);
if(ansFound){
ansFound.count = ansFound.count + 1;
}else{
qFound.answers.push({answer, count:1});
}
}else{
acc.push({
question,
answers: [].concat({answer, count: 1})
});
}
return acc;
},[]);
console.log(res);
推荐阅读
- r - 将数据写入相同xlsx的不同工作表
- r - 如何使用 ggplot 的 `geom_tile()` 更改 NA 正方形颜色
- java - 使用 XmlIo 在 apache 梁中读取 xml 文件
- java - 如何从HashMap中提取数据
在改造 2 中? - r - 从另一个数据框中的 a.character 列创建一个数据框,其中包含 R 中的元素列表
- javascript - 如何使用Javascript动态绘制网格框以对齐网格
- matlab - 如何连接电流测量?
- javascript - Angular RxJs Observable 流合并数据
- python - 使用带有多个组的 pandas 提取正则表达式
- php - 如何解析这种格式?