So I am getting into a bit of object manipulation in JavaScript for the first time and I have a question I'm wondering if anyone could answer.
When I have an object I want to manipulate I could do something to the extent of a few nested for loops, however there are functions built into JavaScript, like map/reduce/filter, and libraries like lodash/underscore.
I assume the latter (map/reduce/filter and the libraries) are better practice but I'm just curious as to why.
I am doing some pretty basic object manipulation that could be solved with a few well placed for loops to grab and change the right keys/values in the object, but can be easily done with the functions/libraries in JS. Just curious as to how they are better - like better performance/cleaner code/ease of use/whatever else.
Apologies, there is no code. I would very much appreciate anyone helping me understand more here.
Edit - so taking from the examples for map()
I could take the example for javascript.map
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;
});
I could do something like
var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = [];
for(var object in kvArray){
//combine both values into object inside of kvArray[object]);
};
A lot less code - but any other benefits worth knowing about?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…