[英]Copy one array values to the the others
我下面有JSON數組。 我想為dayOfWeek
設置schedules
,而其他rooms
的schedules
中沒有這些schedules
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 finalArray = [
{ home1: "05:05", dayOfWeek: 1, away: "20:30", roomId: 1 }, //schedules from room2
{ home1: "06:05", dayOfWeek: 5, away: "21:30", roomId: 1 }, //schedules from room2
{ home1: "07:05", dayOfWeek: 7, away: "22:30", roomId: 1 }, //schedules from room2
{ home1: "05:05", dayOfWeek: 1, away: "20:30", roomId: 3 }, //schedules from room2
{ home1: "06:05", dayOfWeek: 5, away: "21:30", roomId: 3 }, //schedules from room2
{ home1: "07:05", dayOfWeek: 7, away: "22:30", roomId: 3 }, //schedules from room2
]
我已經嘗試過,但是無法正常工作!!! 請幫忙!!!
您可以首先找到source of truth room
的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)
只需遍歷數組。
編輯:通過評論編輯
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);
如果您只是要將其放入新數組中,請執行以下操作:
var schedular = data.rooms[1].schedules
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.