映射对象保留键 [英] Map over object preserving keys
本文介绍了映射对象保留键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
underscore.js中的map
函数(如果使用javascript对象调用)会返回从该对象的值映射的值的数组.
The map
function in underscore.js, if called with a javascript object, returns an array of values mapped from the object's values.
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
是否有一种方法可以保留密钥?即,我想要一个返回的函数
is there a way to make it preserve the keys? ie, I want a function that returns
{one: 3, two: 6, three: 9}
推荐答案
带有下划线
Underscore提供了 _.mapObject
函数来映射值并保留键.
Underscore provides a function _.mapObject
to map the values and preserve the keys.
_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
使用 Lodash
Lodash提供了 _.mapValues
函数来映射值并保留键.
Lodash provides a function _.mapValues
to map the values and preserve the keys.
_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
这篇关于映射对象保留键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文