我正在尝试实现计数器的数组,它将在每个位置保存每个元素在数组中出现的次数。
例如,我有这样的结果:

在此firestore查询中:
useEffect(() => {
firebase
.firestore()
.collection("users")
.doc(uid)
.collection("confirmed-appointments").get().then((querySnapshot) => {
let arrayofServices = [];
querySnapshot.forEach((doc) => {
arrayofServices.push(doc.data().serviceType)
})
console.log("Array of services ", arrayofServices);
setServices(arrayofServices);
})
}, [])我想创建一个数组,为我的数据库中的每个serviceType保存一个计数器。
我认为创建一个包含服务名称和计数器的对象可能更容易,但我不知道如何实现这一点
发布于 2020-10-12 16:50:13
const arrayofServices = ['osher', 'osher', 'yanir', 'dor', 'osher'];
const servicesCounter = arrayofServices.reduce((counterObj, service) => {
if (counterObj.hasOwnProperty(service)) {
counterObj[service] += 1;
return counterObj;
}
return {
...counterObj,
[service]: 1
};
}, {});
console.log(servicesCounter);
https://stackoverflow.com/questions/64314285
复制相似问题