Hello I came across an example on MDN with map and I understand it with regular arrays but this example threw me for a loop.
var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = kvArray.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// reformattedArray is now [{1:10}, {2:20}, {3:30}],
// kvArray is still [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]
Essentially I am not understanding how both the "key" and "value" properties "disappear". I thought that rObj[obj.key] = obj.value; line meant in the original array, find the key's value and replace the original key with the value for that key, and it just seems like I'm really confused at this point. Can someone please explain how they got these values?
rObjis a new, empty object created every time your callback is called.rObj[obj.key] = obj.value;then adds a single property to that object with a property name equal toobj.key...kvArrayobject1 = {key: 'a', value: 'b'}; object2 = {}; object2[object1.key] = object2.value. Makingobject2has no effect onobject1.