我有一个问题和不同答案的数组(我动态构建,因此输入和不同答案的数量可能会有所变化):
我需要一个函数来构建另一个数组对象,其中包含“answer”和“count”。在这种情况下,它将是:
有没有一种简单的方法来做到这一点,而不需要使用直接的循环?
var qaArray = [
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
{ question: "Question", answer: "Answer C"},
{ question: "Question", answer: "Answer A"},
{ question: "Question", answer: "Answer B"},
]
我需要一个函数来构建另一个数组对象,其中包含“answer”和“count”。在这种情况下,它将是:
[
{ answer: "Answer A", count: 3 },
{ answer: "Answer B", count: 4 },
{ answer: "Answer C", count: 2 },
]
有没有一种简单的方法来做到这一点,而不需要使用直接的循环?
lodash
并使用groupBy
轻松执行它。 - Koushik Chatterjee