首页 > 解决方案 > 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 counts 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?

标签: javascriptarraysobject

解决方案


使用一次生成所有计数的对象可能更容易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);


推荐阅读