有没有更好的组合数组的方法?

时间:2019-08-20 10:25:52

标签: arrays typescript

我有两个信息列表:

  • 时间段:其中包含一天中的时间段
  • 约会:其中包含当天的约会列表

我想合并列表

我正在使用的代码有效,除非同时有2个约会。意思是如果slots中两次存在“ 14:00”(这是一个有效的情况),那么最后一个人将在14:00都将他们都填满。

var slots = [
    {timeslot:"14:00",name:""},
    {timeslot:"14:00",name:""}, 
    {timeslot:"15:00",name:""},
    {timeslot:"16:00",name:""}
]

var appointments = [
    {timeslot:"14:00",name:"foo" }, 
    {timeslot:"14:00",name:"bar"},
    {timeslot:"15:00",name:"car"}
]

for (let slot of this.slots) {
  for (let appointment of appoinments) {
    if (slot.timeslot == appointment.timeslot) {
      slot.name = appointment.name
    }
  }
}

所需的输出:

filtered list = [
    {timeslot:"14:00",name:"foo" }, 
    {timeslot:"14:00",name:"bar"},
    {timeslot:"15:00",name:"car"}, 
    {timeslot:"16:00",name:"empty"}
]

2 个答案:

答案 0 :(得分:0)

已更新

const slots = [
  { timeslot: '14:00', name: '' },
  { timeslot: '14:00', name: '' },
  { timeslot: '15:00', name: '' },
  { timeslot: '15:00', name: '' },
  { timeslot: '16:00', name: '' }
];

const appointments = [
  { timeslot: '14:00', name: 'foo' },
  { timeslot: '14:00', name: 'bar' },
  { timeslot: '15:00', name: 'car' }
];

const combined = [];

slots.forEach(slot => {
  const matchingAppointmentIdx = appointments.findIndex((a) => a.timeslot === slot.timeslot);
  if (matchingAppointmentIdx >= 0) {
    combined.push(appointments[matchingAppointmentIdx]);
    appointments.splice(matchingAppointmentIdx, 1);

  } else {
    combined.push({ timeslot: slot.timeslot, name: 'empty' });
  }
});

答案 1 :(得分:0)

更简单:

const slots = [
  { timeslot: '14:00', name: '' },
  { timeslot: '15:00', name: '' }, 
  { timeslot: '16:00', name: '' }
];

const appointments = [
  { timeslot: '14:00', name: 'foo' },
  { timeslot: '14:00', name: 'bar' }, 
  { timeslot: '15:00', name: 'car' }
];

const combined = slots.map(slot => {
  const found = appointments.find(appointment => appointment.timeslot === slot.timeslot);
    return {
      timeslot: slot.timeslot,
      name: found ? found.name : 'empty'
    }
  });


console.log(JSON.stringify(combined, null, 4));