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

问题描述 投票:0回答:2

嗨,我有这个对象数组:

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

该结果或最相似的结果如何可能做到这一点?

javascript arrays reactjs object
2个回答
0
投票

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


0
投票

我不知道。呵呵😁 ...................................................... ...................................................... ...................................................... ................................................

© www.soinside.com 2019 - 2024. All rights reserved.