Search code examples
javascriptnode.jsexpressswig-template

Performing math operations on arrays of objects javascript


Creating an eCommerce/financial based application with node I am having trouble working out how to have a base figure in a static var var budget = 300; and then have the expenses stored in objects in an array

var expenses = [
   {name: "thingy1", price: "40"},
   {name: "thingy2", price: "30"},
   {name: "thingy3", price: "100"}
];

and have the prices deducted from the budget varible and then displayed in the template

p.s im using express and swig


Solution

  • Your question is a little confusing so I hope this is the answer you want, you may want to consider re-wording it.

    var budget = 300;
    var expenses = [
       {name: "thingy1", price: "40"},
       {name: "thingy2", price: "30"},
       {name: "thingy3", price: "100"}
    ];
    expenses.forEach(function (el) {budget -= el.price;});//Removes the price of each expense from the budget