首页 > 解决方案 > 在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);

好吧,它给出了对象中教师出现的频率,但是有没有更好和更有效的方法来完成这项任务

标签: javascriptarraysobjectfrequencyfind-occurrences

解决方案


假设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 })
  ), {})
);


推荐阅读