破坏性地映射对象属性函数 [英] Destructively map object properties function

查看:116
本文介绍了破坏性地映射对象属性函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个示例或解决方案,用于破坏性地映射或更改对象的值,而不是返回新对象或旧对象的副本。可以使用underscore.js,因为项目已经使用这个第三方库。

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.

推荐答案

这就是这样一个解决方案的样子,使用下划线:

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}

工作演示: http://jsbin.com/yubahovogi/edit?js,output

(不要忘记打开您的控制台/ devtools;>)

(don't forget to open your console / devtools ;> )

这篇关于破坏性地映射对象属性函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆