What is the best way to combine an array with an array of objects?

I'm working with two arrays in my code: one is called Indicators and the other is Departments.

My task is to link each department to every indicator. So, if there are 4 departments, I need to create 4 indicators, each with a different department but at the same index. How can I accomplish this?

EDIT: Here's the snippet of my code:

     let departmentArray = []
                         this.DepartmentIR.forEach(entry=>{
                            departmentArray.push(entry.Department)
                         })
                     
                        this.RisksIndicatorsIR.forEach(entry=>{   
                            let temp = {...entry}
                            temp.Departments = departmentArray    
                            console.log(temp)
                        })
                    })

Answer №1

const departmentsList = [
  "departmentA",
  "departmentB",
  "departmentC",
  "departmentD"
];
const metrics = [
  { name: "metrics1", id: 95 },
  { name: "metrics2", id: 92 },
  { name: "metrics3", id: 93 },
  { name: "metrics4", id: 94 }
];

// Utilizing the forEach method to assign all departments to each metric
const updatedMetrics = [];
metrics.forEach((m) =>
  updatedMetrics.push({ ...m, departments: departmentsList })
);

console.log("Updated Metrics using forEach", updatedMetrics);

// Using Reduce to add all departments to each metric
const updatedMetricsArr = metrics.reduce((acc, m) => {
  acc.push({ ...m, departments: departmentsList });
  return acc;
}, []);

console.log("Updated Metrics using Reduce", updatedMetricsArr);

// Adjusting for one department per metric 
const singleDepartmentPerMetric = metrics.reduce((acc, m, i) => {
  acc.push({ ...m, departments: departmentsList[i] });
  return acc;
}, []);

console.log("One Department Per Metric Solution", singleDepartmentPerMetric);

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

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

Retrieve default HTML from an AngularJS directive

Currently, I am in the process of creating an AngularJS directive and require the ability to extract the HTML content of an element before replacing it with a template. For instance: <edit>Default title</edit> The structure of my directive is ...

How can I populate a database with an array of entities using Symfony 3?

I want to include an array field in my database and utilize it similar to how FOSUserBundle handles roles. The objective is to introduce a package table in my User entity without using a join table. I have replicated the schema used for roles and integra ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

Unable to access a two-dimensional array by assigning it to a pointer

I've been attempting to print a two-dimensional array by assigning it to a pointer. Printing a one-dimensional array works fine, but when I try to do the same with a 2D array, I encounter a segmentation fault. void printOutput(int **array,int row, in ...

Compiling C programs with large array lengths, such as 10000, can result in errors when initializing 2-dimensional arrays

I attempted to create a 2-dimensional array with both the inner and outer array size varying from 1 to 100,000. To do this, I declared it in the following way: https://i.sstatic.net/mIiQc.jpg However, I encountered the error: https://i.sstatic.net/MJu7o ...

Adding Angular directives to the DOM after the document has finished loading does not function properly in conjunction with ngAnimate

I've been working on developing an Angular service that can dynamically append a notification box to the DOM and display it without the need to manually add HTML code or write show/hide logic. This service, named $notify, can be used as follows: $no ...

Encountered an issue when trying to establish the session description: An error occurred while attempting to set the remote answer SDP: Request was made in an inappropriate state

Using Angular JS to Get Room Id/Token from Server Side for WebSocket Connection Code Snippet Used in Application - app.controller("videoCallingController", ["$scope", "$location", "$rootScope", "$localStorage", 'AuthenticationService', "CommonS ...

Unable to send a response once the status has been set

I have created a route in my Express application to handle form submissions. I am facing an issue with setting a status and sending a response when an error occurs during the form processing. In the front-end, I am using FormData() and in the back-end, I&a ...

nodemon has encountered an issue and the app has crashed. It is now waiting for any file

I am currently working on creating a to-do application using node.js and mongodb to store user input data in the database. However, I am encountering an error when attempting to run nodemon. As a newcomer to node.js, I may have overlooked something in my c ...

What is the process of retrieving the elements of an array in MATLAB when a Java array is transferred to a MATLAB function using the MATLABcontrol API in Java?

Utilizing the matlabcontrol API within Java to establish a connection between Matlab and Java. The Matlab function is called using returningFeval, where the function name and Object array are passed as parameters. Java Code Object[] path = new Object[2] ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

Encountering an error while submitting form via Ajax to PHP backend

Currently, I am in the process of developing a form that solicits information from a user, including their name, address, amount1, amount2, and a comment. It seems that the radio inputs for amount1 and amount2 are causing issues with my form. Upon submiss ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Generate final string output from compiled template

Check out this template I created: <script type="text/ng-template" id="validationErrors.html"> <div id="validationErrors"> <div id="errorListContainer"> <h2>Your order has some errors:</h2> ...

Is there a way to direct the embedded YouTube video on my HTML website to open in the YouTube application instead?

My website has embedded Youtube videos, but when viewing on a mobile browser they open in the default player. I want them to open in the Youtube application instead, as my videos are 360 degrees and do not work properly in the default browser player. ...

Persistent navigation once fullscreen banner is completed

I have a full screen header on my one-page website. Below the hero section is the navigation element, which I want to be fixed after scrolling past the height of the full screen. Here's what I currently have in terms of code. HTML: <div id="hero" ...

Trouble with Javascript file functioning correctly

I am currently working on a mini game project using HTML, CSS, and JavaScript. Everything seems to be running smoothly with the HTML, CSS, and most of the JavaScript code. However, when I test the program in FireFox and attempt to click on a square div th ...

What is the best way to link a URL ID to a specific piece of content stored on

Is it possible to display a product without creating separate html pages for each one using unique IDs? I prefer the layout style of Pinterest. For example, with a URL like /product/12345 When a user clicks on /product/12345, the content should be rende ...