我的代码:
const orig = {" a ":1, " b ":2}
let result = _.mapKeys(_.mapValues(orig, (v) => v + 1), (v, k) => k.trim())
实际和期望的结果= { “a2, “b”:3 }
但是有更好的Lodashy方式吗?
答案 0 :(得分:8)
此解决方案使用_.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>
&#13;
答案 1 :(得分:2)
为了完整起见,这就是不带破折号的方式:
const orig = {" a ":1, " b ":2};
let result = Object.keys(orig).reduce((r, k) => {
r[k.trim()] = orig[k] + 1;
return r;
}, {})
console.log(result);
如果可以使用IE的polyfill,也可以这样做:
const orig = {" a ":1, " b ":2};
let result = Object.entries(orig).reduce((r, [k, v]) => {
r[k.trim()] = v + 1;
return r;
}, {})
console.log(result);
上述方法的主要问题之一是您需要使用reduce语句返回结果。这不是一个大问题,但会增加行数。一种替代方法如下
const orig = {" a ":1, " b ":2};
let result = {};
Object.keys(orig).forEach(k => result[k.trim()] = orig[k] + 1);
console.log(result);
或
const orig = {" a ":1, " b ":2};
let result = {};
Object.entries(orig).forEach(([k, v]) => result[k.trim()] = v + 1);
console.log(result);
答案 2 :(得分:1)
这样的事情怎么样?
DATETIME
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));
答案 3 :(得分:1)
使用reduce可以:
var obj = {" a ":1, " b ":2}
result = _.reduce(obj, (result, v, k) => {
result[k.trim()] = v + 1
return result
}, {})
console.log(result)
&#13;
<script src="https://cdn.jsdelivr.net/npm/lodash@latest/lodash.min.js"></script>
&#13;
reduce更为熟悉,但IMO转换似乎更合适