Trying to _.invert
an object with lodash, collecting the old keys into an array, rather than losing them.
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?
Use _.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:
_.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'
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.