Destructively map object properties function

2019-07-22 17:44发布

问题:

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 ;> )