如何将数组转换为具有每个键的特定名称的JavaScript对象?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (29)

我正在尝试使用JavaScript将以下数组转换为JavaScript对象,但我不知道该怎么做。

这是我的输入数组。对于此数组,每个键代表一周中的某一天(周日至周六)。所以key 0 = Sunday, key 1 = Monday ....一直到key 6 which = Saturday。

var times = [["8:30-12:00","14:00-18:00"],
["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],
["9:00-21:00"],[],[]];

这是我想将上面的times数组转换为的JavaScript对象:

timeObj = {
  sunday: [
    {
      start: '08:30',
      stop: '12:00'
    },
    {
      start: '14:00',
      stop: '18:00'
    }
  ],
  monday: [
    {
      start: '06:15',
      stop: '9:30'
    },
    {
      start: '13:00',
      stop: '16:00'
    },
    {
      start: '20:00',
      stop: '23:15'
    }
  ],
  tuesday: [],
  wednesday: [
    {
       start: '9:00',
       stop: '21:00'
    }
  ],
  thursday:  [
    {
       start: '9:00',
       stop: '21:00'
    }
  ],
  friday:  [],
  saturday:  []
};

将数组times转换为timeObj对象的最佳方法是什么?

提问于
用户回答回答于

代码:

let dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']

let times = [
  ["8:30-12:00", "14:00-18:00"],
  ["6:15-9:30", "13:00-16:00", "20:00-23:15"],
  [],
  ["9:00-21:00"],
  ["9:00-21:00"],
  [],
  []
]

const res = {}
for (let i = 0; i < 7; i++) {
  const items = []
  res[dayNames[i]] = items
  times[i].forEach(pair => {
    const parts = pair.split('-')
    items.push({
      start: parts[0],
      end: parts[1]
    })
  })
}
console.log(res);
用户回答回答于

我的建议是将Array.prototype.reduce用于1级列表,将Array.prototype.map用于2级列表以创建适当的数组对象:

const data = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

const result = data.reduce((acc, item, index) => { 
  acc[days[index]] = 
    item.map(day => ({ 
      start: day.substr(0, day.indexOf('-')), 
      end: day.substring(day.indexOf('-') + 1)
    }));
  return acc;
 }, {});

扫码关注云+社区

领取腾讯云代金券