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

时间:2017-12-26 10:20:18

标签: javascript lodash

我已经解决了这个问题,但想找到一种更具可读性(可维护性)的方法来写这个:

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

Codepen

2 个答案:

答案 0 :(得分:1)

使用方法链:

constexpr

以下可能在语义上更能表达您的意图:

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



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




答案 1 :(得分:0)

使用链接可以简化它的可读性:

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