Destructively map object properties function

 ̄綄美尐妖づ 提交于 2019-12-11 02:43:09

问题


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



来源:https://stackoverflow.com/questions/30894044/destructively-map-object-properties-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!