Shinji-san Shinji-san - 6 months ago 10
Javascript Question

Understanding map functions with objects: Keys and Values

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?

Answer

You said:

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.


Array.prototype.map doesn't replace. It applies the callback function provided by you on each element from the original array, and pushes the resulting output into a new array. From the docs:

The map() method creates a new array with the results of calling a provided function on every element in this array.

It is important to note that the original array is not meant to be altered by map.