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

时间:2018-08-01 14:54:10

标签: javascript arrays javascript-objects

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

这是我的输入数组。对于此数组,每个键代表一周中的一天(星期日至星期六)。因此,键0 =周日,键1 =星期一....一直到键6,即周六。

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的最佳方法是什么?

3 个答案:

答案 0 :(得分:4)

您可以创建一个对应天的数组并在其上循环。在每次迭代中,在结果对象中创建日期的键,其值将是开始时间和结束时间。

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"],[],[]];
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
var result = {};

days.forEach((day, index) => {
  result[day] = times[index]
    .map(item => {
      let [start, stop] = item.split('-');
      return {start, stop};
    });
});

console.log(result);

答案 1 :(得分:3)

我的建议是将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;
 }, {});

答案 2 :(得分:0)

您在这里:

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