title: JavaScript Object storing only latest value in for loop
body: <p>I'm trying to store every value in an Object when my code parses the information from a database. However, it stores only the latest value. I tried console logging, and it's cycling though the for loop (meaning it outputs 1, 2, 3, 4, and not 4, 4, 4, 4 in the console). I've tried using 'let' instead of 'var' for the variable 'i' in the for loop and declaring the object in the for loop instead of outside the for loop, but to no avail. I think it has something to do with closures in JS, but I don't quite understand it yet.</p>
  <p>Here's my code:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var storage= {};
  var reportRequest = {id 1: 1, id 2: 2, id 3: 3, id 4: 4};
  
          for (let i = 1; i &lt;= 4; i++) {
  
              $.each(reportRequest.storage['id_' + i], function(id, info) {
                      storage[id] = info;
              });
          console.log(storage);
          }</code></pre>
  </div>
  </div>
  </p>
  <p>It console logs '4, 4, 4, 4' (meaning the storage object holds only the value '4' for each cycle of the loop) when Object 'storage' is defined outside the for loop. When it is defined in the for loop, it'll console log '1', then '2', then '3', then '4'. Trying to get it to hold all four values at the same time.</p>