title: JS: how to dynamically add attribute to object
body: <p>I have written a simple JavaScript function to calculate an average of a dataset (see code below). I want to add the result as a new attribute to the object itself but it doesn't work. It seems that the parameter name of the function cannot be used. I don't understand why... what am I doing wrong?</p>
  
  <pre><code>var dataset01 = [{xdis:0,href:20.2},
    {xdis:16.5,href:18.3},
    {xdis:23.9,href:15.7},
    {xdis:36.1,href:13.4}
  ];
  
  function calcAvg(ds,par){
  
      var total = 0;
      for(var i = 0; i &lt; ds.length; i++) {
          total += ds[i][par];
      }
      var avg = total / ds.length;
  
      ds.avg[par]=avg;
  
   }
  
   calcAvg(dataset01,"href");
   calcAvg(dataset01,"xdis");
  </code></pre>
  
  <p>The error being generated</p>
  
  <pre><code>Uncaught TypeError: Cannot set property 'href' of undefined
      at calcAvg ((index):26)
      at (index):30
  </code></pre>