如何在打字稿中比较对象中的多个值

时间:2019-10-22 10:14:07

标签: arrays typescript

我具有以下格式的数据

{
    "monday": "Mon 9 - 12 2 - 4",
    "tuesday": "Tue 9 - 12 2 - 4",
    "wednesday": "Wed 9 - 12 2 - 4",
    "thursday": "Thur 9 - 12 2 - 4",
    "friday": "Fri 9 - 12 2 - 4",
    "saturday": "Sat 9 - 12 2 - 4",
    "sunday": "Sun 9 - 12 2 - 4"
  } 

但我想像这样显示:周一星期六:9-12 2-4

1 个答案:

答案 0 :(得分:1)

您可以创建方法getDaysFormatted,该方法将在两天之内作为参数day1day2

代码:

const weekDays = {
  "monday": "Mon 9 - 12 2 - 4",
  "tuesday": "Tue 9 - 12 2 - 4",
  "wednesday": "Wed 9 - 12 2 - 4",
  "thursday": "Thu 9 - 12 2 - 4",
  "friday": "Fri 9 - 12 2 - 4",
  "saturday": "Sat 9 - 12 2 - 4",
  "sunday": "Sun 9 - 12 2 - 4"
}

const getDaysFormatted = (day1, day2) => {
  const d1 = weekDays[day1].split(' ')
  const d2 = weekDays[day2].split(' ')
  return `${d1[0].toLowerCase()}-${d2[0].toLowerCase()}: ${d1[1]}-${d1[3]} ${d2[4]}-${d2[6]}`
}

// Test
[
  {
    day1: 'monday', 
    day2: 'friday'
   },
  {
    day1: 'monday', 
    day2: 'sunday'
  }
].forEach(({ day1, day2 }) => console.log(getDaysFormatted(day1, day2)))