gpt4 book ai didi

javascript - loDash——有没有一种方法可以简化可读性

转载 作者:行者123 更新时间:2023-11-30 20:52:55 24 4
gpt4 key购买 nike

我已经制定了逻辑,但想找到一种更具可读性(和可维护性)的方式来编写:

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

Codepen

最佳答案

使用方法链:

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

关于javascript - loDash——有没有一种方法可以简化可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47977097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com