javascript - 一个值在对象数组中重复多少次
问题描述
嗨所以我有这个对象数组:
const employees = [
{age: 35, name: "David" position: "Front-End"},
{age: 24, name: "Patrick" position: "Back-End"},
{age: 22, name: "Jonathan" position: "Front-End"},
{age: 32, name: "Raphael" position: "Full-Stack"},
{age: 44, name: "Cole" position: "Back-End"},
{age: 28, name: "Michael" position: "Front-End"},
]
我想得到这样的结果:
const employees = [
{position: "Front-End", count: 3},
{position: "Back-End", count: 2},
{position: "Full-Stack", count: 1},
]
这怎么可能与该结果或最相似的结果有关?
解决方案
const employees = [
{ age: 35, name: 'David', position: 'Front-End' },
{ age: 24, name: 'Patrick', position: 'Back-End' },
{ age: 22, name: 'Jonathan', position: 'Front-End' },
{ age: 32, name: 'Raphael', position: 'Full-Stack' },
{ age: 44, name: 'Cole', position: 'Back-End' },
{ age: 28, name: 'Michael', position: 'Front-End' }
];
const obj = employees.reduce((val, cur) => {
val[cur.position] = val[cur.position] ? val[cur.position] + 1 : 1;
return val;
}, {});
const res = Object.keys(obj).map((key) => ({
position: key,
count: obj[key]
}));
console.log(res);
推荐阅读
- java - 如何在运行时更改此 TRUE 或 FALSE 值
- ios - 如何从 SwiftUI 中的后代视图更改 NavigationViewStyle?
- php - 我们可以使用 jquery 或 php 触发 Chrome 扩展吗
- python - 如何创建一个包含两个字符串之间常见字母的所有可能组合的列表?
- python - 如何获取用户消息并将其用作命令
- com - 为什么 IXMLDOMDocument2->get_documentElement 给我 IXMLDOMElement * 的引用计数设置为 2?
- c++ - 库中所有符号的显式名称修饰(也称为名称修饰)
- angular - Formgroup 中没有 FormArray 的值
- ios - 水平滚动在通过 xcode 为 ios 移动应用程序构建的离子应用程序中不起作用
- javascript - Puppeteer 在尝试截取任何网页时总是超时