如果使用javascript对象调用underscore.js中的map
函数,则会返回从对象的值映射而来的值数组。
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
有没有办法让它保留密钥?即,我想要一个函数,它返回
{one: 3, two: 6, three: 9}
发布于 2014-08-27 19:43:52
var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {
obj[key] = val*3;
return obj;
}, {});
console.log(mapped);
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
发布于 2015-04-24 21:11:19
我知道这是旧的,但现在下划线有了一个新的对象地图:
_.mapObject(object, iteratee, [context])
当然,您可以为数组和对象构建灵活的映射
_.fmap = function(arrayOrObject, fn, context){
if(this.isArray(arrayOrObject))
return _.map(arrayOrObject, fn, context);
else
return _.mapObject(arrayOrObject, fn, context);
}
发布于 2018-02-28 19:01:57
我知道已经有很长一段时间了,但仍然缺少通过fold (在js中也称为reduce )的最明显的解决方案,为了完整起见,我将其留在这里:
function mapO(f, o) {
return Object.keys(o).reduce((acc, key) => {
acc[key] = f(o[key])
return acc
}, {})
}
https://stackoverflow.com/questions/19023226
复制相似问题