javascript - 在javascript中查找对象中键值对的频率

标签 javascript arrays object frequency find-occurrences

想象我有一个对象

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"},
]

现在我如何找到每个 [teacherID: ] 的频率,老师姓名: ],在对象teaherList中

目前我的做法是,
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中查找对象中键值对的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317742/

相关文章:

javascript - 如何使用 Javascript 删除 AWS S3 上的对象?

c - 数组长度变量 - c

java - Java对象数组创建后的内存大小是多少?

c - 如何从文件中获取字符串并将其存储在 2D char 数组中并将该 2D char 数组与 C 中的字符串进行比较?

java - 在 Java 中隐藏名称的误导性示例

javascript - 如果显示最后一行,如何防止jQuery加载更多停止功能

javascript - Angular 功能路由模块 - 未加载子组件

javascript - 如何通过使用Object.defineProperty方法来自定义Array在JavaScript中的行为?

javascript - 如何在reactjs中添加多个对象?

c++ - 使用带有对象 vector 的迭代器c++