删除多余的if对象javascript

问题描述 投票:0回答:1

你好,我有一个想要浏览的对象,当一个值等于 true 时,我填充一个数组。 我的代码可以工作,但我认为放这么多 if 不太好。

daysOfWeek: {
      lundi: true,
      mardi: true,
      mercredi: true,
      jeudi: false,
      vendredi: true,
      samedi: true,
      dimanche: true
    }
 let days = []

    if (daysOfWeek != null) {
        if (daysOfWeek.lundi === true) {
            days.push(2)
        }
        if (daysOfWeek.mardi === true) {
            days.push(3)
        }
        if (daysOfWeek.mercredi === true) {
            days.push(4)
        }
        if (daysOfWeek.jeudi === true) {
            days.push(5)
        }
        if (daysOfWeek.vendredi === true) {
            days.push(6)
        }
        if (daysOfWeek.samedi === true) {
            days.push(7)
        }
        if (daysOfWeek.dimanche === true) {
            days.push(1)
        }
    }
    return days 

days = [2,3,4,6,7,1]

我尝试了开关/外壳,但在某些条件下不起作用。

有人有其他解决方案供我探索吗?

javascript object
1个回答
0
投票
  1. 我建议您对星期日:0 和星期六:6 进行排序和编号,以匹配 JavaScript 的顺序和编号。否则,请像下面一样向索引添加 1。
    请注意,您的示例输出与对象值不匹配

  2. 使用减少:

const daysOfWeek =  {
  dimanche: true,
  lundi: true,
  mardi: true,
  mercredi: true,
  jeudi: false,
  vendredi: true,
  samedi: true
}

// curr is the true/false. I use && to shortcut and the comma operator to return the accumulator
const days = Object.values(daysOfWeek)
  .reduce((acc, curr, index) => (curr && acc.push(index + 1), acc), []);
  
  console.log(days)

© www.soinside.com 2019 - 2024. All rights reserved.