gpt4 book ai didi

javascript - lodash:计算对象数组中的值

转载 作者:行者123 更新时间:2023-11-30 11:58:30 25 4
gpt4 key购买 nike

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

[
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"}
{"question":"Q1","answer":"my answer"}
{"question":"Q2","answer":"answer 2"}
]

我想按问题键分组并返回每个答案的计数。

例如

{
"Q1": [{
"answer": "my answer",
"count": 2
}, {
"answer": "my answer 2",
"count": 1
}],
"Q2": [{
"answer": "answer 2",
"count": 1
}]
}

,

我可以groupBy问题使用:.groupBy("question") 并使用 .countBy() 计算值的出现次数,但我不确定如何结合分组和计数功能来实现所需的输出?

最佳答案

您可以从 _.groupBy(array, 'question') 开始 - 然后使用 .map

例如:

var arr = [
{"question":"Q1","answer":"my answer 2"},
{"question":"Q1","answer":"my answer"},
{"question":"Q1","answer":"my answer"},
{"question":"Q2","answer":"answer 2"}
];

var result = _(arr)
.groupBy('question')
.map(function(item, itemId) {
var obj = {};
obj[itemId] = _.countBy(item, 'answer')
return obj
}).value();

console.log(JSON.stringify(result, null, 2));

查看工作版本:http://jsbin.com/wixoronoqi/edit?js,console

关于javascript - lodash:计算对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com