将一个数组值复制到其他数组值

时间:2018-12-06 07:52:19

标签: javascript arrays loops lodash

我有下面的JSON数组。我想为dayOfWeek设置时间表,而其他schedules的{​​{1}}内部不存在

rooms

我也需要将相同的时间表复制到其他房间。

预期产量

const data = {
  rooms: [
    {
      roomId: 1,
      schedules: []
    },
    {
      roomId: 2,
      schedules: [
        { home1: "05:05", dayOfWeek: 1, away: "20:30" },
        { home1: "06:05", dayOfWeek: 5, away: "21:30" },
        { home1: "07:05", dayOfWeek: 7, away: "22:30" }
      ]
    },
    {
      roomId: 3,
      schedules: []
    }
  ]
}

我已经尝试过,但是无法正常工作!!!请帮忙!!!

3 个答案:

答案 0 :(得分:2)

您可以先找到source of truth room,然后使用Array.reduce提取/复制其他计划:

const data = { rooms: [ { roomId: 1, schedules: [] }, { roomId: 2, schedules: [ { home1: "05:05", dayOfWeek: 1, away: "20:30" }, { home1: "06:05", dayOfWeek: 5, away: "21:30" }, { home1: "07:05", dayOfWeek: 7, away: "22:30" } ] }, { roomId: 3, schedules: [] } ] }

const theRoom = data.rooms.find(x => x.schedules.length)
const result = data.rooms.reduce((r,{roomId, schedules}) => {
  if(roomId != theRoom.roomId)
     r.push(...theRoom.schedules.map(x => ({ roomId, ...x })))
  return r
}, [])
console.log(result)

答案 1 :(得分:1)

只需遍历数组即可。

编辑:通过评论编辑

const data = {
  rooms: [
    {
      roomId: 1,
      schedules: []
    },
    {
      roomId: 2,
      schedules: [
        { home1: "05:05", dayOfWeek: 1, away: "20:30" },
        { home1: "06:05", dayOfWeek: 5, away: "21:30" },
        { home1: "07:05", dayOfWeek: 7, away: "22:30" }
      ]
    },
    {
      roomId: 3,
      schedules: []
    }
  ]
}

var roomIdWithSchedules = null;
var schedulesOfRoomWithRoomIdWithSchedules = [];
for(var i = 0; i < data.rooms.length; i++) {
  if(data.rooms[i].schedules && data.rooms[i].schedules.length) {
    roomIdWithSchedules = data.rooms[i].roomId;
    schedulesOfRoomWithRoomIdWithSchedules = data.rooms[i].schedules.map(function(x) {
      return JSON.parse(JSON.stringify(x));
    });
    break;
  }
}

var finalArray = [];
if(roomIdWithSchedules != null) {
  for(var i = 0; i < data.rooms.length; i++) {
    if(roomIdWithSchedules === data.rooms[i].roomId) {
      continue;
    }
    
    for(var j = 0; j < schedulesOfRoomWithRoomIdWithSchedules.length; j++) {
      var item = JSON.parse(JSON.stringify(schedulesOfRoomWithRoomIdWithSchedules[j]));
      item.roomId = data.rooms[i].roomId;
      finalArray.push(item)
    }
  }
}

console.log(finalArray);

答案 2 :(得分:1)

如果您只是想将其放入新数组中,请执行以下操作:

var schedular = data.rooms[1].schedules