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