为了账号安全,请及时绑定邮箱和手机立即绑定

一个值在对象数组中重复多少次

一个值在对象数组中重复多少次

守候你守候我 2023-11-02 21:30:40
我有这个对象数组: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},]这与该结果或最相似的结果有何关系?
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

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);


查看完整回答
反对 回复 2023-11-02
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信