我试图从forEach
javascript 中的循环创建一个对象,在这个简单的对象中,我试图将count
数组中每个项目的所有s相加。
目前,我正在一个离子(角度/打字稿)项目中使用 firebase,我正在从 firebase 返回一组项目。数组看起来像这样:
[
{
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"
}
}
]
以下是我如何浏览这些项目(result
即项目列表):
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
};
});
现在,我需要增加计数,根据它们的类型将每个部分的计数添加到最后。本typeObj
应该是这个样子。
{
esc: {
count:5
},
camera: {
count:10
}
}
我尝试将计数添加到计数中,如下所示:
typeObj[part.data().type] = {
'count': typeObj[part.data().type].count + part.data().count
};
但是当我第一次制作对象时它不承认有一个计数。(我认为)。
有什么建议吗?
Array#reduce
由于要将数组转换为单个对象,因此可以使用它来完成此操作:
const array = [
{
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"
}
}
];
const typeObj = array.reduce((obj, { specs: { count, type } }) => {
obj[type] = obj[type] || { count: 0 };
obj[type].count += count;
return obj;
}, {});
console.log(typeObj);
它所做的是分配obj[type]
给它自己,或者如果它还不存在,则分配一个新对象{ count: 0 }
。然后它通过数据中指定的计数增加 的count
属性obj[type]
。
如果您有一个data
返回带有数据的对象的方法(正如您在问题中似乎有的那样),您可以像这样修改它:
const typeObj = array.reduce((obj, item) => {
const { type, count } = item.data().specs;
obj[type] = obj[type] || { count: 0 };
obj[type].count += count;
return obj;
}, {});
console.log(typeObj);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句