简体   繁体   English

loDash -- 有没有办法简化可读性

[英]loDash -- Is there a way to simplify for readability

I have the logic worked out but wanted to find a more readable (and maintainable) way to write this:我已经解决了逻辑,但想找到一种更具可读性(和可维护性)的方式来写这个:

let labels = _.map(_.keys( _.groupBy(sd, 'month')), (i) => {
      return months[i].abr;
    });

Codepen代码笔

Use method chaining:使用方法链:

const labels = _(sd).groupBy('month').keys().map(i => months[i].abr);

The following might semantically even better express your intention:以下可能在语义上更好地表达您的意图:

const labels = _(sd).map('month').uniq().map(i => months[i].abr);

 const months = [ {}, { abr: 'Jan', full: 'January' }, { abr: 'Feb', full: 'February' }, { abr: 'Mar', full: 'March' }, { abr: 'Apr', full: 'April' }, { abr: 'May', full: 'May' }, { abr: 'Jun', full: 'June' }, { abr: 'Jul', full: 'July' }, { abr: 'Aug', full: 'August' }, { abr: 'Sep', full: 'Septmeber' }, { abr: 'Oct', full: 'October' }, { abr: 'Nov', full: 'November' }, { abr: 'Dec', full: 'December' } ]; const sd = [ { id: 1, year: 2017, month: 10, service: 3, val: 20 }, { id: 2, year: 2017, month: 10, service: 1, val: 50 }, { id: 3, year: 2017, month: 10, service: 2, val: 25 }, { id: 4, year: 2017, month: 11, service: 3, val: 40 }, { id: 5, year: 2017, month: 11, service: 1, val: 30 }, { id: 6, year: 2017, month: 11, service: 2, val: 35 }, { id: 7, year: 2017, month: 12, service: 3, val: 30 }, { id: 8, year: 2017, month: 12, service: 1, val: 20 }, { id: 9, year: 2017, month: 12, service: 2, val: 50 } ]; const labels1 = _(sd).groupBy('month').keys().map(i => months[i].abr); console.log(labels1); const labels2 = _(sd).map('month').uniq().map(i => months[i].abr); console.log(labels2);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

It could be simplified for readability using chaining:可以使用链接来简化可读性:

let labels = _(sd)
    .groupBy('month')
    .keys()
    .map(key => months[key])
    .value();

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

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