I have an array of rooms of an asylum.
var rooms = [
{
"id": 1001,
"room": "room 1"
},
{
"id": 1002,
"room": "room 2"
},
{
"id": 1003,
"room": "room 3"
},
{
"id": 1004,
"room": "room 4"
}
];
And I also have a list of patients of that 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 belongs to a specific room. I wanna add those patients under their rooms and make a new array which looks like this:
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": []
}
]
That's my expected output but I'm not exactly getting that. This is the code I wrote to achieve the desired result.
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 made a Fiddle. I have printed the array in console. Only one element is getting pushed.