Lodash映射键和对象上的值

时间:2017-07-27 18:16:23

标签: javascript lodash

我的代码:

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

实际和期望的结果= {   “a2,   “b”:3 }

但是有更好的Lodashy方式吗?

4 个答案:

答案 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;
&#13;
&#13;

答案 1 :(得分:2)

为了完整起见,这就是不带破折号的方式:

解决方案1:Object.keys和reduce

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);

解决方案2:Object.entries&reduce

如果可以使用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);

解决方案3:使用Array.forEach的Object.keys / Object.entries

上述方法的主要问题之一是您需要使用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可以:

&#13;
&#13;
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;
&#13;
&#13;

reduce更为熟悉,但IMO转换似乎更合适