In my scenario, I am working with an array of rooms within an asylum.
var rooms = [
{
"id": 1001,
"room": "room 1"
},
{
"id": 1002,
"room": "room 2"
},
{
"id": 1003,
"room": "room 3"
},
{
"id": 1004,
"room": "room 4"
}
];
Furthermore, there is a list of patients associated with this asylum.
var patients = [
{
"id": 10,
"room": "room 1",
"patient_name": "John"
},
{
"id": 11,
"room": "room 1",
"member_name": "Jane"
},
{
"id": 12,
"room": "room 1",
"member_name": "Joe"
},
{
"id": 20,
"room": "room 2",
"patient_name": "Matt"
},
{
"id": 30,
"room": "room 3",
"patient_name": "Alexa"
}
];
Each patient is assigned to a specific room. My goal is to organize these patients under their respective rooms and create a new array structure as follows:
var asylum = [
{
"id": 1001,
"room": "room 1",
"patients": [
{
"id": 10,
"room": "room 1",
"patient_name": "John"
},
{
"id": 11,
"room": "room 1",
"member_name": "Jane"
},
{
"id": 12,
"room": "room 1",
"member_name": "Joe"
}
]
},
{
"id": 1002,
"room": "room 2",
"patients": [
{
"id": 20,
"room": "room 2",
"patient_name": "Matt"
}
]
},
{
"id": 1003,
"room": "room 3",
"patients": [
{
"id": 30,
"room": "room 3",
"patient_name": "Alexa"
}
]
},
{
"id": 1004,
"room": "room 4",
"patients": []
}
]
I have shared the code snippets that are intended to achieve this result, but it seems like I am encountering issues in implementation.
for (var i = 0, len = rooms.length; i < len; i++) {
for (var j = 0, len2 = patients.length; j < len2; j++) {
if (rooms[i].room === patients[j].room) {
rooms[i].members = patients[j];
}
}
}
I created a Fiddle to troubleshoot the problem. Upon inspecting the console output, it appears that only one element is being pushed, which deviates from my expected outcome.