What is the best way to combine two arrays containing objects?

I currently have two arrays containing objects:

let employees = [
  { name: 'Jason', job_id: '101' },
  { name: 'Sarah', job_id: '102' },
  { name: 'Jack', job_id: '102' }
]

let jobs = [
  { job_id: '101', position: 'Designer' },
  { job_id: '102', position: 'Developer' }
]

Is there a way for me to merge these arrays using vanilla javascript, as shown below:

let employees = [
  { name: 'Jason', job_id: [job_id: '101', position: 'Designer'] },
  { name: 'Sarah', job_id: [job_id: '102', position: 'Developer'] },
  { name: 'Jack', job_id: [job_id: '102', position: 'Developer'] }
]

The code snippet I have now does work correctly, but if possible, I would prefer not to rely on nested loops.

employees.forEach(employee => {
  for (let index = 0; index < jobs.length; index++) {
    if (employee.job_id == jobs[index].job_id) {
      employee.job_id= jobs[index];
    }
  }
})

Answer №1

Completing this task is relatively straightforward, so I will provide a simple answer with a live demonstration.

The approach involves iterating through the employees array and constructing objects with the desired structure, then pushing them into a final array.

Each object in the final array will include the following attributes:

  • name: corresponds to the name in the employees array (for each iteration)
  • job: for clarity, I will use job instead of job_id as indicated in your expected output. The job attribute is an object that includes
    • id: representing the job_id from the employees array
    • position: indicating the relevant position from the jobs array

To achieve the above outcome, we will utilize the reduce method to build the final array incrementally.

Furthermore, obtaining the corresponding position from the jobs array based on the job_id from the employees table can be accomplished using the find method which returns the first matching element from the jobs array.

With that explanation in mind, let's proceed with a live demonstration (including instructive comments):

const employees = [{
      name: 'Jason',
      job_id: '101'
    },
    {
      name: 'Sarah',
      job_id: '102'
    },
    {
      name: 'Jack',
      job_id: '102'
    }
  ],
  jobs = [{
      job_id: '101',
      position: 'Designer'
    },
    {
      job_id: '102',
      position: 'Developer'
    }
  ],
  /** 
   * "res" represents the resulting array after performing necessary operations 
   * The "reduce" method traverses the "employees" array to populate the "res" array accordingly
   */
  res = employees.reduce((a, c) => {
    /**
     * a: holds the prior value from the previous iteration - initially set to an empty array "[]" (referenced in the 3rd argument passed to the "reduce" method)
     * c: denotes the current element from the "employees" array for each iteration
     */

    /** appends an object adhering to the intended structure to the final array */
    a.push({
      name: c.name,
      job: {
        id: c.job_id,
        /** 
         * Locate the respective "position" based on the "job_id" of the current element within the "employees" array 
         * el: references the element from the "jobs" array during each iteration of the "find" method
         * the condition checks for an element where "job_id" matches the current element's "job_id," subsequently returning the associated "position"
         * once the "position" is found, it is assigned to the object being constructed
         */
        position: jobs.find(el => el.job_id == c.job_id).position
      }
    });
    /** return the array to enable the next iteration of "reduce" to proceed */
    return a;
  }, []);

/** display the result */
console.log(res);

While the presented demo is one way to accomplish the task, there are undoubtedly alternative ES6 methods available for crafting objects. For simplicity's sake, I have opted for straightforward and comprehensible approaches without utilizing intricate techniques.

For further insight, explore the reduce method documentation on MDN.

Delve into details about the find method via MDN resources.

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

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

What could be causing the Google API to malfunction in my Universal Windows App?

Error: 0x800a138f - JavaScript runtime error: Unable to access 'setApiKey' property of undefined or null reference Hello, I am struggling to make this work on my Universal Windows App. There is a sample for Google's URL shortener with instr ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

How to customize the checkbox color in Material UI?

I've been attempting to adjust the color of checkboxes and radio buttons. After conducting some research, I stumbled upon this helpful link: Material UI change Input's active color Unfortunately, I keep encountering the following error: (0 , _ ...

Angular2 Dropdown not updating with values from API

Here is the structure of my project flow: import_product.html <div class="row custom_row"> <div class="col-md-2">Additional Duty: </div> <div class="col-md-2"> < ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...

The documentation for the 4-11.4 version of Material UI cannot be found anywhere

After the release of MUI v5.0.0-rc.1, it appears that all documentation pages for version 4, except for v4.12.3, have vanished. https://mui.com/versions/ Furthermore, (currently not accessible) Is there a way to access previous versions' document ...

Utilizing ngModel on input elements inside a custom directive, ensuring compatibility with other ng-* attributes

In my current project, I am working on developing a custom directive that acts as a wrapper around an input field. The main purpose of this directive is to simplify formatting, encapsulate animations, and enhance overall functionality. One of my goals for ...

What is the best way to retrieve the values from the labels for two separate buttons?

I designed a pair of buttons with a single label below. Both buttons acted as standalone entities. <label for="buttons" class ="val">0</label> <input class="btn btn-primary button1" type="button" ...

Combining Protractor, CucumberJS, and Gulp-Protractor results in the browser not closing when a test fails

Hello! I am facing an issue with closing the browser when a test fails. Currently, the browser closes successfully when the test passes. The dependencies I am using are: "cucumber": "^0.9.2", "gulp": "~3.9.0", "gulp-protractor": "^2.1.0", "protractor": ...

Guide to implementing input fields in a form in React.js when the user chooses the "Other" option from a dropdown menu

For my project, I have implemented a multi-select dropdown input feature that saves all selected items in a useState array when the user clicks on the add icon. However, I am facing an issue where I need to render an input field only when the "Other" optio ...

Tips for maintaining a loading screen for longer than 4 seconds?

I want to maintain the loading screen for a minimum of 4 seconds. However, the timer at the end does not seem to be functioning as expected. Here is the code snippet I am using: window.addEventListener("load", () => { const preload = document.querySe ...

Updating the initialState in your application while employing the useState function with React Hooks

I'm currently facing an issue with updating the image value in the local state. Everything works fine initially, but once I return to the same page, the initialState seems to retain the previous value. To resolve this, I find myself having to assign t ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

What is the best way to prepopulate form values in a Vue object?

Sharing my code snippet: HTML: <div id="user-panel"> <div class="text-center"> {{ fillItem }} </div> <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:s ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...