Destructively Map Object Properties Function
I was looking for an example or solution for mapping or changing values of an object 'destructively' instead of returning a new object or copy of the old object. underscore.js can
Solution 1:
This is how one such solution could look like, using underscore:
functionmapValuesDestructive (object, f) {
_.each(object, function(value, key) {
object[key] = f(value);
});
}
an example mapper function:
functionsimpleAdder(value) {
return value + 1;
}
and example usage as follows:
var counts = {'first' : 1, 'second' : 2, 'third' : 3};
console.log('counts before: ', counts);
// counts before: Object {first: 1, second: 2, third: 3}mapValuesDestructive(counts, simpleAdder);
console.log('counts after: ', counts);
//counts after: Object {first: 2, second: 3, third: 4}
working demo: http://jsbin.com/yubahovogi/edit?js,output
(don't forget to open your console / devtools ;> )
Post a Comment for "Destructively Map Object Properties Function"