javascript - 在javascript中查找对象中键值对的频率
问题描述
想象我有一个对象
teaherList = [
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
]
现在我如何在对象teaherList中找到每个[teacherID:,teacherName: ]的频率
目前我的情况是,
let temp = []
_.each(teaherList, function(k){
temp.push(k.teacherID)
)
let count1 = countBy(temp);
好吧,它给出了对象中教师出现的频率,但是有没有更好和更有效的方法来完成这项任务
解决方案
假设teaherList
是一个对象数组,这是一种不需要依赖于库的方法,并且还一次性创建输出对象(总迭代次数 = 数组长度),具有reduce
:
const teaherList = [
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
];
console.log(
teaherList.reduce((a, { teacherName }) => (
Object.assign(a, { [teacherName]: (a[teacherName] || 0) + 1 })
), {})
);
推荐阅读
- javascript - 如何在使用纯 JavaScript 时对定义文件进行类型检查?
- r - R,在文本中搜索特定大小的单词,nchar函数
- migration - Truffle migrate --reset 不会丢失数据
- excel - 用户表单没有在我的 excel 表中插入数字
- c# - 如何自动为项目中的每个方法添加属性?
- solidity - 在 remix.ethereum 中调用外部函数
- javascript - 将数据从主函数传递到 getServerSideProps
- c++ - Visual C++ MFC CScrollView:插入符号停止闪烁
- c - C编程:在第一个空格之前删除字符串
- python - 如何从 DurationField 的总和中获取总秒数的查询集