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 be used since the project already uses this third party library.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This is how one such solution could look like, using underscore:
function mapValuesDestructive (object, f) {
_.each(object, function(value, key) {
object[key] = f(value);
});
}
an example mapper function:
function simpleAdder (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 ;> )