I'm currently working on creating an object using a forEach
loop in JavaScript. The goal is to total up all the count
s for each item in the array and store them based on their type.
My project involves using Firebase in an Ionic (Angular/TypeScript) app, where I retrieve an array of items from the database. Here's an example of what the array structure looks like:
[
{
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"
}
},
...
]
To achieve this, I am iterating through these items (result
being the list of items):
let partArr = [];
let typeObj = {};
result.forEach(part => {
//Adding parts to the list
partArr.push({
'id':part.id,
'specs':part.data(),
});
//Creating a list based on types
typeObj[part.data().type] = {
'count': 0
};
});
The next step is to increment the counts by adding each part's count to the last count based on their type. The typeObj
should be structured like this:
{
esc: {
count:5
},
camera: {
count:10
}
}
When trying to update the count, I encountered a problem where it didn't recognize the count when initially creating the object. Any tips or advice would be greatly appreciated!