Javascript variable copying and data being overwritten in array
<p>I already have a solution, but I want to understand the <i>why</i>.</p>

<pre><code>var returnObj = {};
//declare object
var copyObj = {};
    for (var k in data.data) {
        for (var i = 0; i &lt; data.data[k].offerId.length; i++) {
            if (obj.hasOwnProperty(data.data[k].offerId[i])) {
                (function() {
                    var offerId = data.data[k].offerId[i];
                    var verticalId = k;

                    copyObj = obj[offerId];

                    //this does not work - overwrites similar object in array
                    if (returnObj[offerId] !== undefined) {
                        copyObj.value = 'something';
                        returnObj['copy'] = copyObj;
                    } else {
                        copyObj.value = 'something else';
                        returnObj[offerId] = copyObj;
                    }
                })();
            }
         }
     }
</code></pre>

<p>So my question is, what is going on with the scope and the variable reference that causes my attempt at creating a new slot in the array for an object that already exists, to overwrite the already existing object in the array? My <code>copyObj.value</code> will be the <code>something</code> at both <code>returnObj['copy']</code> and <code>returnObj[offerId]</code>. </p>

<p>I have a solution already, and that is to use <code>angular.copy()</code>, but I wanted to know why updating the <code>copyObj</code> would affect the previously stored value?</p>

<p>Is there any other way to copy the object (instead of using <code>angular.copy()</code>)?</p>