javascript - Javascript - Making an object and incrementing count in an array for each loop
问题描述
I am trying to create an object from a forEach
loop in javascript and in this simple object, I am trying to add up all of the count
s for each item in the array.
Currently, I'm using firebase in an ionic (angular/typescript) project and I am returning an array of items from firebase. The array looks something like this:
[
{
id:'uniqueID',
specs: {
count:5,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Foxeer Cam 2",
type:"camera"
}
},
{
id:'uniqueID',
specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Furibee 40a",
type:"esc"
}
},
{
id:'uniqueID',
specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Runcam Cam 1",
type:"camera"
}
},
{
id:'uniqueID',
specs: {
count:1,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Hobbywing 4 in 1",
type:"esc"
}
}
]
Here's how I'm running through these items (result
being the list of items):
let partArr = [];
let typeObj = {};
result.forEach(part => {
//Put all parts in a list
partArr.push({
'id':part.id,
'specs':part.data(),
});
//Put all types in a list
typeObj[part.data().type] = {
'count': 0
};
});
Now, I need to increment the count, adding each part's count to the last depending on their type. The typeObj
should look something like this.
{
esc: {
count:5
},
camera: {
count:10
}
}
I tried adding the count to the count like so:
typeObj[part.data().type] = {
'count': typeObj[part.data().type].count + part.data().count
};
but it does not recognize there being a count when I'm first making the object. (I think).
Any advice?
解决方案
使用一次生成所有计数的对象可能更容易reduce
,并且每次迭代只调用.data()
一次:
const results = [
{
data() { return { specs: {
count:5,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Foxeer Cam 2",
type:"camera"
}}}},
{
data() { return { specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Furibee 40a",
type:"esc"
}}}},
{
data() { return { specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Runcam Cam 1",
type:"camera"
}}}},
{
data() { return { specs: {
count:1,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Hobbywing 4 in 1",
type:"esc"
}}}}
];
const typeObj = results.reduce((a, item) => {
const { count, type } = item.data().specs;
if (!a[type]) a[type] = { count: 0 };
a[type].count += count;
return a;
}, {});
console.log(typeObj);
推荐阅读
- wordpress - 如何根据wordpress中的当前帖子自动选择一个值?
- python - Can´t excecute view action in Django
- react-router-dom - 如何让这个滑出导航菜单与 react-router 和 framer-motion 一起使用?
- arrays - for循环中有两个if语句?
- javascript - 我如何使用结构扩展我的 jsx 元素
- r - 删除纵向数据中的不连续时间点
- python - Python jupyter 网络服务器在 3-5 秒后停止
- python - 然后在条件下读取 sheet_names 列表
- python - SqlAlchemy 递归查询
- sql - IF 函数格式 SQL 出错:不支持错误 BOOL、STRING、BOOL,仅 IF(BOOL、ANY、ANY)