简体   繁体   English

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. 我试图通过javascript中的forEach循环创建一个对象,并且在这个简单的对象中,我试图将数组中每个项目的所有count加起来。

Currently, I'm using firebase in an ionic (angular/typescript) project and I am returning an array of items from firebase. 目前,我正在离子(角度/打字稿)项目中使用Firebase,并且正在从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): 这是我运行这些项目的方式( 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
  };

});

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. typeObj应该看起来像这样。

{
    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? 有什么建议吗?

It would probably be easier to use reduce to generate the object with the counts all at once, and to call .data() only once on each iteration: 使用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); 

You can use Array#reduce to accomplish this since you want to transform an array into a single object: 您可以使用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); 

What this does is assign obj[type] to either itself or if it doesn't yet exist, a new object { count: 0 } . 这是将obj[type]分配给它本身,或者如果尚不存在,则分配一个新对象{ count: 0 } Then it increments the count property of obj[type] by the specified count in the data. 然后,它将obj[type]count属性增加数据中的指定计数。

If you have a data method that returns an object with the data (as you seem to have in the question), you can modify it like so: 如果您有一个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM