Lodash中的物体逆变器,不会丢失钥匙

时间:2018-03-23 19:59:44

标签: javascript lodash

尝试使用lodash _.invert一个对象,将旧密钥收集到一个数组中,而不是丢失它们。

以下是我设法做到的事情:



let tokens = {
    y: 'years',
    Y: 'years',
    M: 'months',
    mo: 'months',
    Mo: 'months',
    w: 'weeks',
    W: 'weeks',
    d: 'days',
    D: 'days',
    h: 'hours',
    H: 'hours',
    m: 'minutes',
    mi: 'minutes',
    Mi: 'minutes',
    s: 'seconds',
    S: 'ms'
  },
  print = JSON.stringify(inverter(tokens), null, 2);

document.querySelector('#test').innerHTML = print;

function inverter(obj) {
  let out = {};
  _.forOwn(obj, (o, k) => {
    out[o] = _.concat(out[o] || [], [k]);
  });
  return out;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

<pre id="test"></pre>
&#13;
&#13;
&#13;

大多数时候我觉得我对lib的使用具有游泳锤的优雅,所以我的问题是:是否更简单,更优雅&#34; lodashy&#34; < / em>方式比我当前的inverter()函数?

2 个答案:

答案 0 :(得分:3)

使用_.invertBy()。根据文件:

  

每个反转键的相应反转值是一个数组   负责产生倒置值的密钥。

&#13;
&#13;
const tokens = {"y":"years","Y":"years","M":"months","mo":"months","Mo":"months","w":"weeks","W":"weeks","d":"days","D":"days","h":"hours","H":"hours","m":"minutes","mi":"minutes","Mi":"minutes","s":"seconds","S":"ms"};
  
const result = _.invertBy(tokens);

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

<pre id="test"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用Lodash 4.1.0或更高版本,你应该能够做到:

_.invertBy({
  y: 'years',
  Y: 'years',
  M: 'months',
  mo: 'months',
  Mo: 'months',
  w: 'weeks',
  W: 'weeks',
  d: 'days',
  D: 'days',
  h: 'hours',
  H: 'hours',
  m: 'minutes',
  mi: 'minutes',
  Mi: 'minutes',
  s: 'seconds',
  S: 'ms'
});