Combining object properties from a collection of objects based on matching IDs in JavaScript

I have two arrays of objects that I need to merge together based on matching typeId values. The first array contains information about different states, while the second array contains information about state types. The goal is to combine the properties of the matching state types into the corresponding state objects, appending "stateType" to the property name if necessary. Let me illustrate this with an example.

Array of objects

"states": [
        {
            "id": 1,
            "typeId": 1,
            "name": "CREATED",
            "description": "Created",
            "label": "Created",
            "perviousNotMatchKey": "Text"
        },
        {
            "id": 2,
            "typeId": 3,
            "name": "ASSIGNED",
            "description": "Assigned",
            "label": "Assigned",
            "perviousNotMatchKey": "Text"
        },
        {
            "id": 3,
            "typeId": 3,
            "name": "COMPLETED",
            "description": "Completed",
            "label": "Completed",
            "perviousNotMatchKey": "Text"
        }
    ],
    "stateTypes": [
        {
            "id": 1,
            "name": "PENDING",
            "description": "Pending",
            "label": "Pending",
            "newIncomingKey": "Text"
        },
        {
            "id": 2,
            "name": "IN_PROGRESS",
            "description": "In Progress",
            "label": "In Progress",
            "newIncomingKey": "Text"
        },
        {
            "id": 3,
            "name": "COMPLETED",
            "description": "Completed",
            "label": "Completed",
            "newIncomingKey": "Text"
        }
    ],

Wanted array

 "newArray": [
        {
            "id": 1,
            "typeId": 1,
            "name": "CREATED",
            "description": "Created",
            "label": "Created",
            "perviousNotMatchKey": "Text",
            "newIncomingKey": "Text",
            "stageType-id": 1,
            "stageType-name": "PENDING",
            "stageType-description": "Pending",
            "stageType-label": "Pending"
        },
        {
            "id": 2,
            "typeId": 3,
            "name": "ASSIGNED",
            "description": "Assigned",
            "label": "Assigned",
            "perviousNotMatchKey": "Text",
            "newIncomingKey": "Text",
            "stageType-id": 3,
            "stageType-name": "COMPLETED",
            "stageType-description": "Completed",
            "stageType-label": "Completed"
        },
        {
            "id": 3,
            "typeId": 2,
            "name": "COMPLETED",
            "description": "Completed",
            "label": "Completed",
            "perviousNotMatchKey": "Text",
            "newIncomingKey": "Text",
            "stageType-id": 2,
            "stageType-name": "IN_PROGRESS",
            "stageType-description": "In Progress",
            "stageType-label": "In Progress"
        }
    ],

Answer №1

Here is an example of how it could look like:

const data = [
        {
            "id": 1,
            "typeId": 1,
            "name": "CREATED",
            "description": "Created",
            "label": "Created",
            "perviousNotMatchKey": "Text"
        },
        {
            "id": 2,
            "typeId": 3,
            "name": "ASSIGNED",
            "description": "Assigned",
            "label": "Assigned",
            "perviousNotMatchKey": "Text"
        },
        {
            "id": 3,
            "typeId": 3,
            "name": "COMPLETED",
            "description": "Completed",
            "label": "Completed",
            "perviousNotMatchKey": "Text"
        }
];
const types = [
        {
            "id": 1,
            "name": "PENDING",
            "description": "Pending",
            "label": "Pending",
            "newIncomingKey": "Text"
        },
        {
            "id": 2,
            "name": "IN_PROGRESS",
            "description": "In Progress",
            "label": "In Progress",
            "newIncomingKey": "Text"
        },
        {
            "id": 3,
            "name": "COMPLETED",
            "description": "Completed",
            "label": "Completed",
            "newIncomingKey": "Text"
        }
];

const tempData = {};

for (const item of data) {
  tempData[item.id] = { ...item };
}

for (const type of types) {
  const dest = tempData[type.id];

  for (const [key, value] of Object.entries(type)) {
    if (dest[key]) dest[`types-${key}`] = value;
    else dest[key] = value;
  }
}

const updatedData = Object.values(tempData);

console.log(updatedData);

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

Display an additional HTML page without altering the existing one

First of all, I would like to apologize for my poor English. Attending a French school didn't provide much opportunity to practice other languages. I have a header.html on my website that I am unable to modify because it is not owned by me. However, ...

Discover the importance of Node.js integration with HTML

I am trying to display a Node-js value in an HTML file using the pug engine. In my app.js file: const express=require('express'); const app=express(); var bodyParser = require('body-parser'); app.set('views','views&apo ...

Investigating the variety of HTTP 206 responses pertaining to video content

Currently, I am utilizing Amazon CloudFront to serve HTML5 videos. These videos are being requested through HTTP range requests and the expected responses are often in the form of HTTP 206 Partial Content. I have a requirement where I want to log the requ ...

Efficiently Manipulating Arrays in JavaScript

After reading a .csv file and saving it to an array, I encountered the following array structure: var data = [["abc;def"],["ghi;jkl"], ...] The strings within the nested arrays are separated by semicolons. In order to work with this da ...

mention a particular anchor by clicking on it to refresh the webpage

Can a webpage automatically navigate to a specific anchor/tag when reloaded in the browser? Thanks in advance I came across this method: window.location.reload(); However, I'm searching for a solution that can detect the reload and then run a basi ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

Is the array State not setting properly in React Native?

I apologize for the strange request, but I need help with a validation method for form inputs within a modal. Currently, I am checking each this.state.variable and pushing them to an aux array, which is then supposed to be set to the original fieldErrors ...

d3 bar chart with overlapping bars - define x and y coordinates

Here is a glimpse of the data I am working with: var students = [ {'race': 'Black', 'count': 7, 'year': 2004, 'allnames': ['G Brown', 'F Clarkson', 'E Miller', 'R Black& ...

Is there a way to assign the value of a textfield to a session attribute in JSP prior to rendering?

Imagine I have the following code snippet: <html> <head> <script> function setSession() { var roll=document.getElementById("rollno").value; session.setAttribute("rollno", roll); } & ...

Unable to insert controller into routeprovider

Currently, I am working on an exercise in AngularJS to enhance my skills focusing on routes. However, I am facing issues with getting the controller attributes to function correctly inside the routed template. Despite reading numerous tutorials, the code s ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...

Characteristics within the primary template element of a directive

I'm having an issue with the following directive code: .directive('myDirective', function () { restrict: 'E', replace: true, transclude: true, scope: { label: '@', ngModel: '=', ...

How can I create a reverse animation using CSS?

Is there a way to reverse the animation of the circular notification in the code provided? I want the circle to move forward, covering up the info and fading out. I've tried switching the animation around but haven't had success. Any suggestions? ...

What is the solution for resolving the Next.js 14 next/link routing 404 error page problem?

After performing a fresh installation of Next.js on Windows using an elevated shell with the command npx create-next-app@latest, I encountered an issue. In my /src/app/components/Header.tsx file, the code looks like this: import React from 'react&apos ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

Transmitting PHP arrays to JavaScript through AJAX

I am struggling to retrieve an array from a SQL server using PHP and parse it to JavaScript using AJAX. Despite trying various solutions found through Google, I have been unable to successfully retrieve the array. Below is my PHP code: <?php inclu ...

Organize JSON information in a tabular layout

After resolving my previous issue, I am now attempting to store JSON data in cookies and then retrieve it to organize the variables in tabular form. However, I am uncertain about how to go about arranging it. View the demonstration here ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

I'm wondering if you have any insights on how to retrieve objects using Mono WebAssembly

I am looking to send a c# object back via mono-wasm, but when I attempt to do so, the returned object appears in my JavaScript file here. The C# code can be found in [image2]: C# code My JavaScript code can be found here: JS code Everything seems to wor ...

Alter the border color of a bootstrap-div using JavaScript

I need to update the border color of a div element, but I'm encountering issues when using a bootstrap class on the div. Is there a way to change the border color using Javascript? <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/ ...