xua*_*nji 126 javascript underscore.js lodash
mapunderscore.js中的函数,如果使用javascript对象调用,则返回从对象的值映射的值数组.
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
Run Code Online (Sandbox Code Playgroud)
有没有办法让它保存钥匙?即,我想要一个返回的函数
{one: 3, two: 6, three: 9}
Run Code Online (Sandbox Code Playgroud)
GG.*_*GG. 222
使用Underscore
Underscore提供了_.mapObject映射值和保留键的功能.
_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
Run Code Online (Sandbox Code Playgroud)
随着Lodash
Lodash提供了_.mapValues映射值和保留键的功能.
_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
Run Code Online (Sandbox Code Playgroud)
xua*_*nji 56
我设法在lodash中找到了所需的函数,这是一个类似于下划线的实用程序库.
http://lodash.com/docs#mapValues
Run Code Online (Sandbox Code Playgroud)_.mapValues(object, [callback=identity], [thisArg])使用与通过回调运行对象的每个自己的可枚举属性而生成的对象和值相同的键创建对象.回调绑定到thisArg并使用三个参数调用; (价值,关键,对象).
kun*_*ani 19
var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {
obj[key] = val*3;
return obj;
}, {});
console.log(mapped);Run Code Online (Sandbox Code Playgroud)
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>Run Code Online (Sandbox Code Playgroud)
Ray*_*jax 13
我知道这是旧的,但现在Underscore有一个新的对象地图:
_.mapObject(object, iteratee, [context])
Run Code Online (Sandbox Code Playgroud)
您当然可以为阵列和对象构建灵活的映射
_.fmap = function(arrayOrObject, fn, context){
if(this.isArray(arrayOrObject))
return _.map(arrayOrObject, fn, context);
else
return _.mapObject(arrayOrObject, fn, context);
}
Run Code Online (Sandbox Code Playgroud)
Rot*_*eti 12
普通JS(ES6/ES2015)中的这个版本怎么样?
let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * 3})));
Run Code Online (Sandbox Code Playgroud)
如果要以递归方式映射对象(映射嵌套的obj),可以这样做:
const mapObjRecursive = (obj) => {
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object') obj[key] = mapObjRecursive(obj[key]);
else obj[key] = obj[key] * 3;
});
return obj;
};
Run Code Online (Sandbox Code Playgroud)
从ES7/ES2016开始,您可以使用Object.entries而不是Object.keys像这样:
let newObj = Object.assign(...Object.entries(obj).map([k, v] => ({[k]: v * 3})));
Run Code Online (Sandbox Code Playgroud)
小智 5
我知道这已经很长时间了,但是仍然缺少通过 fold(在 js 中也称为 reduce)的最明显的解决方案,为了完整起见,我将其留在这里:
function mapO(f, o) {
return Object.keys(o).reduce((acc, key) => {
acc[key] = f(o[key])
return acc
}, {})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107204 次 |
| 最近记录: |