简体   繁体   English

Lodash中的对象逆变器而不会丢失密钥

[英]Object inverter in lodash without losing keys

Trying to _.invert an object with lodash, collecting the old keys into an array, rather than losing them. 尝试使用_.invert对象,将旧键收集到一个数组中,而不是丢失它们。

Here's how I managed to do it: 这是我设法做到的方法:

 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> 

Most of the time I feel my usage of the lib has the elegance of a swimming hammer, so my question would be: is there's a simpler, more elegant "lodashy" way than my current inverter() function? 大多数时候,我感觉到我对lib的使用就像一把游泳锤一样优雅,所以我的问题是:有没有一种比我当前的converter inverter()函数更简单,更优雅的“ lodashy”方式?

Use _.invertBy() . 使用_.invertBy() According to the docs: 根据文档:

The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. 每个反转键的相应反转值是负责生成反转值的键的数组。

 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); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script> <pre id="test"></pre> 

With Lodash 4.1.0 or greater you should be able to just do: 使用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'
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM