Tips for combining arrays of objects

I have two arrays containing objects

const obj = {
    teamRows: [
        {name: 'Alice', admin_id: 1},
        {name: 'Bob', admin_id: 2},
        {name: 'Charlie', admin_id: 3},
    ],
    roleRows: [
        {title: 'Manager', role_id: 1},
        {title: 'Supervisor', role_id: 2},
        {title: 'Coordinator', role_id: 3},
    ]
};

I am looking to combine the objects from both arrays like this. Each object in teamRows corresponds to an object in roleRows

const newArr = [
    {name: 'Alice', admin_id: 1, title: 'Manager', role_id: 1},
    {name: 'Bob', admin_id: 2, title: 'Supervisor', role_id: 2},
    {name: 'Charlie', admin_id: 3, title: 'Coordinator', role_id: 3},
]

Answer №1

In the case where the length of each array is the same, a straightforward solution utilizing Array#map can be implemented like so:

const obj = {
    teamRows: [
        {name: 'Sarah', admin_id: 3},
        {name: 'Jack', admin_id: 4},
        {name: 'Emily', admin_id: 5},
    ],
    roleRows: [
        {title: 'Manager', role_id: 5},
        {title: 'Supervisor', role_id: 6},
        {title: 'Coordinator', role_id: 7},
    ]
};


// Each teamRow is mapped to a new object by merging it with the corresponding roleRow (by index)
const newArr = obj.teamRows.map((teamRow, index) => 
    ({ ...teamRow, ...obj.roleRows[index] }))

console.log(newArr);

Answer №2

To streamline the object, you have the option to reduce all values.

const
    object = { teamRows: [{ name: 'Adam', admin_id: 3 }, { name: 'Bob', admin_id: 4 }, { name: 'Ivan', admin_id: 5 },], roleRows: [{ title: 'Lead Bizdev', role_id: 5 }, { title: 'Lead', role_id: 6 }, { title: 'Integration', role_id: 7 }] },
    result = Object
        .values(object)
        .reduce((a, b) => a.map((o, i) => Object.assign({}, o, b[i]));

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

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

Observing data within an AngularJS service

I am currently working with a service called sharedData and a controller named HostController. My goal is to have the HostController monitor the saveDataObj variable within the sharedData service, and then update the value of host.dataOut, which will be re ...

Arranging array positions in ThreeJS

My BufferGeometry contains an array of x/y/z positions with almost 60,000 points (18,000 values), [3, 2, 1, 3, 2, 1, 3, 2, 1, ...] To obtain random points, I am considering shuffling these positions and then selecting the first 30,000. One idea is to fir ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

Is there an undefined error when clicking on a row in a dynamically created table?

When creating a table and adding a row click event with the purpose of retrieving the value of the first td, the following code is used: function bclick(){ var result=[]; SAPget.step4QueryTable(function(data){ var tbody=document.querySelector( ...

Executing jQuery after the body has finished loading

I'm trying to execute a JavaScript function once the body has finished loading. My framework loads the header and footer from static files, while the body content is dynamic. I read online that I should place the $(elem).load(function()) at the end of ...

What are the steps to integrate the vue-tweet-embed node package into vuejs2?

I am having trouble figuring out how to implement the vue-tweet-embed plugin in my Vue file. I keep getting an error message that says: Unknown custom element: - have you properly registered the component? If dealing with recursive components, ensure ...

What method does jQuery Validation use to configure the validation message?

A custom method was developed for the jQuery validation plugin to validate whether a given value meets the length requirements set during validation. The method is structured as follows: jQuery.validator.addMethod("exactLength", function(value, ...

Encountering an undefined array within a click function nested inside a for loop

Being a newbie in this field, I seem to have overlooked a simple detail. The for loop is functioning correctly, but within it, I encounter an issue with an undefined variable. var categories_info = ["history","excellence","art","social","facilities","p ...

Is it possible to divide a column in an HTML table into two separate

I am currently working with an array of elements that I need to iterate over. For each element, I create a <td></td> tag. When dealing with 10 elements, it results in a table with one column and 10 rows. Is there a method, using either HTML o ...

Using Jquery to toggle columns based on their index and custom attribute

My table has two rows in the header: the first row with colspan and the second row containing headers. You can see an image below for reference. https://i.sstatic.net/qwSBL.png With a jQuery function, I extract all the table cell values from the second h ...

What is the best way to restrict datalist options while preserving the "value" functionality?

After finding a creative solution by @Olli on Limit total entries displayed by datalist, I successfully managed to restrict the number of suggestions presented by a datalist. The issue arises from the fact that this solution only covers searching through ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

Error: The SpringBoot API returned a SyntaxError because an unexpected token < was found at the beginning of the JSON response

I am currently following a tutorial on Spring Boot React CRUD operations which can be found here. However, I have encountered an issue when trying to fetch JSON data from the REST API and display it in my project. Despite following the steps outlined in th ...

Understanding the scope of variables in HTML files, JavaScript files, and PHP files when echoing statements

Is there a way to define a global javascript variable that can be accessed from multiple places within an HTML page? I need the variable to be accessible in three specific locations: Within the code of the HTML page favorites.php. Inside a separate javas ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

"Subtle Website Background Fade Effect When Menu is Hovered Over

Click on the following link to observe a transition effect that occurs on the body of the website when interacting with the main menu system: Here is the website Do you know what this effect is called and how it can be integrated into a website? ...

Branding image from Bootstrap overlapped with a container situated below the navigation bar

I'm having trouble adding a 400 x 100 png logo as a Navbar Brand image in Bootstrap 5. The logo is appearing too large, and even when I try to resize it, it still overlaps the black container and text input box below the Navbar in desktop view. On mob ...

Why is this component not functioning properly?

I am struggling with making a function to add a component dynamically when I click a button, similar to the code below. However, my attempt at creating a separate method for adding the component instead of using an inline expression is not working. Can som ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...