0

I am turning an array of objects in to an object of objects. I added my question inside the code for better understanding.

var arr = [ 
  {key : '11', value : '1100', $$hashKey : '00X' },
  {key : '22', value : '2200', $$hashKey : '018' }
];

var result = {};
for (var i = 0; i < arr.length; i++) {
  result[arr[i].key] = arr[i];
}

// below changes the original array (arr)

result["11"]["value"]="mike"

// below DOES NOT change the original array (arr)

result["2222"] = {key: "33", value: "deded"}

console.log(arr)

I just dont understand why. I have never assigned result to arr (thus created reference to original array), so why does original array change?

Thanks a lot!

javascripting
  • 1,135
  • 4
  • 25
  • 46
  • Objects are never deep-cloned unless you do so explicitly. `arr` is an array of two objects. In your first code, `result` is an object whose two values point to the exact same objects in memory. So if you mutate any of the objects in `result`, you're also mutating an object in `arr` – CertainPerformance Nov 30 '19 at 22:04
  • When you assign each object row from arr to result you are making a reference - `result[arr[i].key] = arr[i];` – Joe Nov 30 '19 at 22:04
  • *side note*: if you like the "functional" style you can use [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) fo this usecase – jcal Nov 30 '19 at 22:08
  • Thank you. I actually believed that if I dont just assignarr array to result array (thus making reference), but iterate through arr, creating a new object result, then I am deep cloning so after I can change properties on result array without affecting original array. How would I need to do it so that I am not pointing to the original array? Thanks a lot!! – javascripting Dec 01 '19 at 09:22

0 Answers0