Failed to push an array of objects into another array in JavaScript

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.

Answer №1

Ensure you are correctly updating the rooms[i].members value whenever a new patient is identified. Modify your code to include pushing the new patient into the array:

for (let i = 0; i < rooms.length; i++) {
  for (let j = 0; j < patients.length; j++) {
    if (rooms[i].room === patients[j].room) {
        if (!rooms[i].members) { //initialize the array when the first patient is found for this room
            rooms[i].members = [];
        }
        rooms[i].members.push(patients[j]);
    }
  }
}

Answer №2

In order to efficiently organize the patients into rooms, you can implement a solution using a hash table and a two-loop method. First, generate an asylum array by assigning a hash value to each room. Then use a second loop to allocate patients to their respective rooms.

var rooms = [{ id: 1001, room: "room 1" }, { id: 1002, room: "room 2" }, { id: 1003, room: "room 3" }, { id: 1004, room: "room 4" }],
    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" }],
    hash = Object.create(null),
    asylum = rooms.map(function (o) {
        return hash[o.room] = { id: o.id, room: o.room, patients: [] };
    });

patients.forEach(function (o) {
    hash[o.room].patients.push(o);
});

console.log(asylum);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Loop through the list of patients and for each patient, compare their assigned room with the available rooms. If a match is found, include the patient in the corresponding room's list.

var rooms = [{"id": 1001, "room": "room 1"}, {"id": 1002, "room": "room 2"}, {"id": 1003, "room": "room 3"}, {"id": 1004, "room": "room 4"}];

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"}];
  
patients.forEach(patient => {
    var room = rooms.find(room => patient.room === room.room);
    
    if(room) {
         
       if(!room.patients) {
          room.patients = [];
       }
      
       room.patients.push(patient);
    }

 });
 
 console.log(rooms);

Answer №4

My code snippet showcases the importance of consistency with variable names, as using "patient_name" and "member_name" interchangeably can lead to errors.

    var asylum = [];


 var rooms = [
    {
      "id": 1001,
      "room": "room 1"
    },
    {
      "id": 1002,
      "room": "room 2"
    },
    {
      "id": 1003,
      "room": "room 3"
    },
    {
      "id": 1004,
      "room": "room 4"
    }
  ];

 var patients = [
    {
        "id": 10,
        "room": "room 1",
        "patient_name": "John"
    },
    {
        "id": 11,
        "room": "room 1",
        "patient_name": "Jane"
    },
    {
        "id": 12,
        "room": "room 1",
        "patient_name": "Joe"
    },
    {
        "id": 20,
        "room": "room 2",
        "patient_name": "Matt"
    },
    {
        "id": 30,
        "room": "room 3",
        "patient_name": "Alexa"
    }
  ];
  
  var asylum = [];
  
var aRoomWithPatients,apatient,rooma,roomb,name;
for (var i = 0; i < rooms.length; i++) {
   aRoomWithPatients = {};
   aRoomWithPatients.id = rooms[i].id;
   aRoomWithPatients.room = rooms[i].room;
   aRoomWithPatients.patients = [];
   asylum.push(aRoomWithPatients);
  for (var j = 0; j < patients.length;  j++) {
  rooma = rooms[i].room;
  roomb = patients[j].room;
  name = patients[j].patient_name;
    if (rooma === roomb) {
apatient = {};
apatient.id = patients[j].id;
apatient.room = patients[j].room;
apatient.patient_name = name;
        asylum[i].patients.push(apatient);
    }
  }
}
console.log(asylum);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Should information be retrieved from the server or the client side?

Allow me to clarify the situation at hand. I am currently developing a website where users can store movie information, sourced from a third-party API known as The Movie Database. At this juncture, my main concern pertains to optimizing performance throu ...

"Flaw discovered in Python's Lottery Program due to a logic

I have been working on a code where the user is required to input 6 'lottery' numbers ranging from 1 to 59, and the computer generates 6 random numbers within the same range. The program then needs to compare the two sets of numbers to determine ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

Fixed Position - Make width match the container's dimensions

I've been experimenting with setting a div's position to fixed once a user has scrolled a certain distance. I've run into an issue where the fixed position div's width doesn't match its parent element. How can I ensure that the fix ...

When attempting to perform a second addition operation on the Angular calculator, it fails to work. However, each addition works perfectly when done individually

I have encountered a curious issue with my Angular calculators. Individually, they both function perfectly as intended. However, when I attempt to combine them, one always malfunctions. Is there something crucial that I am overlooking in this scenario? (D ...

Is there a way to verify the content inside the :before selector using Jasmine within an Angular 6 application?

Looking to test whether the content of a label changes based on the checkbox being checked using Jasmine in an Angular 6 project. Is this feasible? Code snippet: HTML <input id="myCheck" class="checkbox" type="checkbox" /> <label for="myCheck" ...

Iterate through every item in Google Docs and duplicate them onto a fresh page

I am currently developing a script that allows teachers to easily create translations of documents stored on Google Drive. The script is expected to go through the body elements of the document, translate the text, and paste it onto a new page appended to ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

Show a loading progress image during the page loading process (not during form submission)

Is there a way to show a loading GIF image while a page is loading or during postbacks using jQuery and JavaScript for long running tasks or processes that take a significant amount of time to execute? I attempted a solution but the loading image is not d ...

Executing multiple asynchronous calls in parallel in Node.js, with the ability to prioritize their

Imagine using Node.js to execute two asynchronous calls in order to retrieve some information. You could utilize the async package, where you simply pass two functions and an optional callback. async.parallel([fun1(){callback(null,1);}, fun2(){callback(nu ...

Retrieving the value of an array from a string pattern using PHP

I have an assumption about an array: Array ( [0] => john [1] => robinson [2] => 27-08-1980 [3] => football [4] => pizza ) I am interested in extracting values from the array usin ...

Debugging client-side TypeScript with Node

Is it possible to debug client-side .ts typescript files directly from Visual Studio (2015) with breakpoints and watches? Most solutions online recommend using browser devtools like Chrome. But can it be done in Visual Studio? After creating a .ts script ...

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

Ways to determine the existence of five consecutively increasing values in a vector

I have a vector and I'm trying to determine if there are any sequences of five consecutive numbers where the values are in increasing order (sorted). While I've come up with a solution, I believe that there is likely another more efficient approa ...

Refreshing material ui select choices based on user input

Just getting started with Reactjs and I need some help. I have a material ui select element that has default values set, and when I click the 'ADD USER' button and submit, I can add new values to the select element. I'm also able to delete o ...

The error message is indicating that the function "req.assert" is not

Can you identify the issue with this code snippet (express 4.16.0, TypeError: req.assert is not a function)? userController.signupPost = function(req, res, next) { console.log(req.body); var express=require('express'); var validator = require(&a ...

What is the best method to design a navigation bar that is responsive to different screen

I'm facing a challenge with making my website responsive. I've successfully made all the pages responsive, but I'm struggling to finalize the navigation part. You can view my website at www.christierichards.co.uk/gcc_website/index.php When ...

What is the reason behind the quicker search for the median in a 100-item array compared to a 10-item array?

I conducted experiments to verify this, and the results were not entirely as anticipated: http://jsperf.com/value-in-array-or-object Feel free to run your own tests as well. ...

Issue with React form not appearing on web browser

I'm having trouble getting the form to show up on the browser. For some reason, the formComponentDict variable is not displaying any of the form steps. Can anyone point me in the right direction? Any assistance would be greatly appreciated. Thank you ...

Having trouble changing the title with Switch/Case in Angular?

I am facing an issue where the title is not displayed as expected based on the environment value in appConfig.json. appConfig.json "env": "stage", app.component.ts env: string; constructor( private configService: ConfigService ) ...