2017-07-27 127 views
3

我的代码:Lodash地图的键和值

const orig = {" a ":1, " b ":2} 
let result = _.mapKeys(_.mapValues(orig, (v) => v + 1), (v, k) => k.trim()) 

实际和期望的结果= { “一”:2, “B”:3 }

但有一个更好的Lodashy这样做的方式?

+0

可能不是不幸ly:https://github.com/lodash/lodash/issues/2718 – user3080953

回答

4

该解决方案使用_.transform(),它有点短。我不确定它比你的功能性解决方案更好。

const orig = {" a ": 1, " b ": 2 }; 
 

 
const result = _.transform(orig, (r, v, k) => r[k.trim()] = v + 1); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

1

怎么这样呢?

const orig = {" a ":1, " b ":2}; 
 

 
function test(object) { 
 
    let out = {}; 
 

 
    _.forEach(object, function(value, key) { 
 
    out[key.trim()] = value + 1; 
 
    }); 
 

 
    return out; 
 
} 
 

 
console.log(test(orig));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

0

使用减少,你可以这样做:

var obj = {" a ":1, " b ":2} 
 

 
result = _.reduce(obj, (result, v, k) => { 
 
    result[k.trim()] = v + 1 
 
    return result 
 
}, {}) 
 

 
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

减少是比较熟悉的,但IMO变换似乎在这里更合适