计算数组中答案的冗余度

时间:2019-04-07 11:13:10

标签: javascript arrays sorting

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

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

我已经尝试解决此问题,但是我无法提供任何帮助。谢谢

2 个答案:

答案 0 :(得分:1)

我们可以使用Array.find查找问题答案对,然后添加 new 问题答案对对象(如果该对不存在)或更新该对象现有的问答对对象。

如果问题仍然存在,但答案没有答案,那么只需在answers数组中添加新答案即可。

如果问题和答案都同时存在,则将答案count属性增加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);
   

答案 1 :(得分:0)

使用reduce创建按问题和答案值分组的对象,然后稍后放弃使用keys的{​​{1}}

Object.values()