首页 > 解决方案 > 计算数组中答案的冗余

问题描述

我有一个像这样的对象数组

 [
{_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}]
 }
]

我试图解决这个问题,但我不能,所以任何帮助将不胜感激。谢谢

标签: javascriptarrayssorting

解决方案


如果该对不存在,我们可以使用它Array.find来查找问答对,然后添加一个的问答对对象,或者更新现有的问答对对象。

如果问题存在但答案不存在,则只需在answers数组中添加新答案。

如果问题和答案都存在,则将 answercount属性增加 1。

如果问题本身缺失,则添加一个具有question属性和answers属性的新对象并将其设置count1.

然后最后使用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);
   


推荐阅读