Using JavaScript, store access keys and labels in an object. Then, iterate over a separate array and assign the access keys and labels to each element within the array during

In my code, I have an object named roomDetails that contains various room labels. My goal is to extract the label from this object and then assign it as the value of the roomLabel property in each item of the patientArray.

roomDetails = {
    room01{label: "Room 1"},
    room02{label: "Room 2"},
    room03{label: "Room 3"},
    room04{label: "Room 4"}
}


let patientArray = [

{ roomLabel: '', name: 'John'},
{ roomLabel: '', name: 'Shawn'},
{ roomLabel: '', name: 'Gereth'},
{ roomLabel: '', name: 'Elminster'}
]

The desired output for the patientArray should be:

let patientaArray = [
    { roomLabel: 'Room 1', name: 'John'},
    { roomLabel: 'Room 2', name: 'Shawn'},
    { roomLabel: 'Room 3', name: 'Gereth'},
    { roomLabel: 'Room 4', name: 'Elminster'}
]

I've made attempts using JavaScript but encountered issues with overwriting values. Here is part of my existing code:

Object.keys(roomDetails).map((key, index) => {

    const roomLabel = roomDetails[key].label;

    patientArray.forEach((pi, index) => {

        pi.roomLabel = roomDetails[key].label;

    });
});

I need assistance in finding a solution that preserves the correct values without overwriting them. Any guidance would be greatly appreciated. Thank you.

Answer №1

roomDetails is not considered an object in your current code.

The provided snippet may not be robust enough as it does not handle varying lengths of the roomDetails object and patientArray. It would be advisable to come up with a more comprehensive algorithm that can account for all possible scenarios.

Furthermore, it's recommended not to alter the original patientArray data - creating a copy of it is a better practice (map() generates a new array with modified values; leaving patientArray unchanged).

const roomDetails = {
  room01: {
    label: "Room 1"
  },
  room02: {
    label: "Room 2"
  },
  room03: {
    label: "Room 3"
  },
  room04: {
    label: "Room 4"
  }
}

const patientArray = [{
    roomLabel: '',
    name: 'John'
  },
  {
    roomLabel: '',
    name: 'Shawn'
  },
  {
    roomLabel: '',
    name: 'Gereth'
  },
  {
    roomLabel: '',
    name: 'Elminster'
  }
]

const finalArray = Object.values(roomDetails).map((e, i) => {
  return {
    roomLabel: e.label,
    name: patientArray[i].name
  }
})

console.log(finalArray)

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

What strategies can I implement to optimize my code's performance with the help of arrays?

As a novice programmer, I'm looking to optimize my code. How can I create arrays for the final ints PIECE1 - PIECE 8 and the images image1 - image8? Additionally, what is the best way to call g.drawImage just once instead of repeating it 8 times with ...

JavaScript is causing issues preventing the automated test from setting the input

While creating an automation script using Ruby with Selenium, Watir, and Cucumber, I encountered a test failure caused by a change in a text field. The issue arose because a Javascript function was triggered upon interacting with the field, restricting inp ...

What is the method for verifying the return value against a specific string value?

I need to verify the return value of a method against either "Yes" or "No", should I use an equals comparison or a regex matching the pattern like Yes or No. Here is my code snippet: if ((ru.getTest()).equals(("Yes") || (“No”))) {...... Is ...

After installing babylonjs via npm, encountering the error 'Unable to utilize import statement outside a module'

Recently, I've been working on setting up babylonjs through npm. Starting with a new project, I ran npm init and then proceeded to install babylonjs using npm install babylonjs --save, following the provided documentation. I then created a JavaScript ...

React.js - Error message: onChange is not defined

My application has successfully integrated the last.fm API to fetch related artists. The concept is simple - search for an artist and receive a list of related artists in return. While using 'onClick' works flawlessly as it retrieves the input v ...

Can you convert a preprocessor to an array?

Can a preprocessor be cast to an array? This question arises as I attempt to convert a preprocessor to an array. Specifically, I am uncertain about the feasibility of this task, given the preprocessor defined as Number 0x44332211. Below is the code snipp ...

Is There a Lack of 'Contains' Support in JavaScript's ScriptEngine?

Below is some code that I am working with. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("[1, 2, 3].contains(1)"); However, when I run the code, it throws the following e ...

Instructions for activating a button in the absence of any inputs

I need help enabling a button in angularjs based on whether any of the inputs are filled out. I was successful in disabling a button when only one input is checked, but how can I do this for all inputs affecting one button? This is what I've attempted ...

Challenges with ColdFusion's floating point calculations

I am encountering an issue with my program where it is not displaying two decimal points properly. For example, when I enter 140.00, it shows as 140.0. Strangely, if I enter 140.15, it displays correctly as 140.15. It seems to consistently drop the zero. B ...

Using Selenium in JavaScript, extracting content from a specific class tag

Currently, I am using Selenium Webdriver in JS to scrape data from a website. My goal is to determine the number of <tr> tags that contain exactly three children. <tr> <td>One</td> <td>Two</td> </tr> <tr> ...

`Creating a fluid MySQL table using JavaScript`

One of the challenges I'm facing involves working with a MySQL table that consists of 3 columns: MySQL db table +--+----+-------------+ |id|data|display_order| +--+----+-------------+ |0 |0 |2 | +--+----+-------------+ |1 |1 |1 ...

Issue encountered when setting up Webpack development server resulted in the failure to generate

Is anyone else experiencing difficulties when trying to create a static folder named "dist"? Package.json "scripts": { "start": "webpack-dev-server --open", "dev": "webpack --mode development --watch ./frontend/src/index.js --output ./frontend/static/fr ...

Preventing User Duplication in MERN Stack: Strategies to Avoid Multiple Registrations

A developer fairly new to the field is working on a project using the MERN stack. Within this app, there are two models: one for Users and another for Tournaments. The Tournament model contains an attribute called participants, which is an array. The dev ...

Having difficulty sorting data with Firebase in a VueJS project

I'm a newcomer to VueJS and I've encountered an issue when attempting to call the OrderBy method using VueJS. My basic application is fetching a simple array of items that are being displayed in a table: <!DOCTYPE html> ...

Optimizing Window Width with React.js and CSS

I'm currently in the process of building a responsive website with react. I am utilizing CSS stylesheets for styling and have used @media queries to ensure responsiveness. However, I've encountered an issue while testing in Chrome where the elem ...

What is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

Effortlessly verify checkboxes associated with the corresponding ID in the database

I am currently facing a challenge while working on a project using Codeigniter that I need help resolving. Here is the issue: In the view above, you can see multiple roles and permissions displayed. Each role has its own set of permissions stored in the ...

A guide on dynamically sending data to a PHP script when an input is changed and displaying the results in a

I am trying to implement a feature where the data inputted into a text field is sent to posttothis.php and then the result is displayed in a content div. However, I am encountering difficulties in making it work. testscript.html <html> <head> ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...

Tips on passing an array as an argument to a function

I am interested in learning how to pass an array as input to a function in Go and utilize it within the function. function PassingArrayToFunction(arr []int) ...