Home > Enterprise >  How can I add values to an object without overwriting the previous one in a loop?
How can I add values to an object without overwriting the previous one in a loop?

Time:10-08

Take the following code:

export const BOMs: BOM[] = [
   { part_num: "X-Wing", sub_part_num: "Max Engine", qty: 4 },
   { part_num: "X-Wing", sub_part_num: "Airplane Body", qty: 1 },
   { part_num: "Tie Fighter", sub_part_num: "Max Engine", qty: 2 },
   { part_num: "Tie Fighter", sub_part_num: "Airplane Body", qty: 1 },
];

export const Sales: Sale[] = [
  { part_num: "X-Wing", qty: 100 },
  { part_num: "Tie Fighter", qty: 200 },
];

function generate_report(boms: BOM[], sales: Sale[]) {

   let myObj = {};
   BOMs.map(bom => {
      sales.map(sale => {
          if (sale.part_num === bom.part_num)  {
              myObj[bom.sub_part_num] = bom.qty * sale.qty  
              myObj[bom.part_num] = sale.qty; 

          }
      })
  })

  return myObj;
}


// myObj {
     'Max Engine': 400,
     'X-Wing': 100,
     'Airplane Body': 200,
     'Tie Fighter': 200
   }

My test expects myObj to return

expect(results["Max Engine"]).toBe(100 * 4   200 * 2); // 800

This number assumes qty of 400 for "X-Wing" and 400 for "Tie Fighter". What's happening is my loop is overwriting the value of Max Engine in the X-wing and only returns the value for the Tie Fighter, which is 200 x 2 = 400.

How can I alter my code so these values are concatenated?

CodePudding user response:

You want

myObj[bom.sub_part_num] = bom.qty * sale.qty 

to instead be

if (!myObj[bom.sub_part_num]) {
    myObj[bom.sub_part_num] = 0;
}
myObj[bom.sub_part_num]  = bom.qty * sale.qty;

or more succinctly:

myObj[bom.sub_part_num] = (myObj[bom.sub_part_num] || 0)   bom.qty * sale.qty
  • Related