What is the best way to combine two arrays of objects with varying values for the same key, and add a new object to the mix?

I have two arrays:

arr1 = [
  {
    "OwnershipNumber": 0,
    "ID": null,
    "Name": "Contractor LLC",
    "ContrEmployeeTypeId": 0,
    "ContactEmail": "",
    "ContactPhone": "",
    "VeteranEmployeeMilitaryAffiliation": "",
    "SocialSecurityNumber": "",
    "DrivingLicense": "",
    "DateOfBirth": null,
    "OwnershipPercentage": 0,
    "IsContractorActive": "Y",
    "VeteranFlag": "N",
    "VeteranEmployeeHireDate": null,
    "LegalIssueFlag": "N",
    "ActiveFlag": true,
    "TimeStamp": null
  },
  {
    "OwnershipNumber": 1878,
    "ID": null,
    "Name": "Greg Dawson",
    "ContrEmployeeTypeId": 2,
    "ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52222033123330317c313d3f">[email protected]</a>",
    "ContactPhone": "455-455-6444",
    "VeteranEmployeeMilitaryAffiliation": null,
    "SocialSecurityNumber": "454534245",
    "DrivingLicense": "44524245",
    "DateOfBirth": "11/30/1968 12:00:00 AM",
    "OwnershipPercentage": 100,
    "IsContractorActive": "Y",
    "VeteranFlag": "N",
    "VeteranEmployeeHireDate": null,
    "LegalIssueFlag": "N",
    "ActiveFlag": true,
    "TimeStamp": null
  }
]


arr 2 = [ {"OwnershipNumber": 1878, "ContactPhone": "111-222-6444"},
 {
    "OwnershipNumber": null,
    "ID": 3,
    "SocialSecurityNumber": "465464654",
    "DrivingLicense": "464654654654",
    "DateOfBirth": "1998-12-12T18:30:00.000Z",
    "VeteranEmployeeHireDate": "1970-01-01T00:00:00.000Z",
    "Name": "Tom Hanks",
    "ContrEmployeeTypeId": 1,
    "IsContractor": "N",
    "ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43372c2e03242e222a2f6d202c2e">[email protected]</a>",
    "ContactPhone": "564-465-4654",
    "OwnershipPercentage": 100
  }
]

I am trying to accomplish this after merging and pushing:

arr3 = [
      {
        "OwnershipNumber": 0,
        "ID": null,
        "Name": "Contractor LLC",
        "ContrEmployeeTypeId": 0,
        "ContactEmail": "",
        "ContactPhone": "",
        "VeteranEmployeeMilitaryAffiliation": "",
        "SocialSecurityNumber": "",
        "DrivingLicense": "",
        "DateOfBirth": null,
        "OwnershipPercentage": 0,
        "IsContractorActive": "Y",
        "VeteranFlag": "N",
        "VeteranEmployeeHireDate": null,
        "LegalIssueFlag": "N",
        "ActiveFlag": true,
        "TimeStamp": null
      },
      {
        "OwnershipNumber": 1878,
        "ID": null,
        "Name": "Greg Dawson",
        "ContrEmployeeTypeId": 2,
        "ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c1c3d0f1d0d3d29fd2dedc">[email protected]</a>",
        "ContactPhone": "111-222-6444",
        "VeteranEmployeeMilitaryAffiliation": null,
        "SocialSecurityNumber": "454534245",
        "DrivingLicense": "44524245",
        "DateOfBirth": "11/30/1968 12:00:00 AM",
        "OwnershipPercentage": 100,
        "IsContractorActive": "Y",
        "VeteranFlag": "N",
        "VeteranEmployeeHireDate": null,
        "LegalIssueFlag": "N",
        "ActiveFlag": true,
        "TimeStamp": null
      },
{
    "OwnershipNumber": null,
    "ID": 3,
    "SocialSecurityNumber": "465464654",
    "DrivingLicense": "464654654654",
    "DateOfBirth": "1998-12-12T18:30:00.000Z",
    "VeteranEmployeeHireDate": "1970-01-01T00:00:00.000Z",
    "Name": "Tom Smith",
    "ContrEmployeeTypeId": 1,
    "IsContractor": "N",
    "ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebaa1a38ea9a3afa7a2e0ada1a3">[email protected]</a>",
    "ContactPhone": "564-465-4654",
    "OwnershipPercentage": 100
  }
    ]

The first array (arr1) serves as the master array, while the second array (arr2) contains only the changes that have been made in relation to the first array. For example, you can see that ownership number 1878 has a change in the ContactPhone field. Therefore, ContactPhone along with OwnershipNumber is present in arr2. It can also include a new object like the one with the name field Tom Smith (which does not exist in arr1). The goal is to merge the changes based on the OwnershipNumber and ContactEmail, and add any new elements like the object with the name field Tom Smith into the new array (arr3). The changes and inclusion of new elements are optional, so arr2 may be blank. Your assistance with this would be greatly appreciated.

Answer №1

It is my understanding that the OwnershipNumber serves as a unique key to identify which object you intend to modify (or add, if the number does not yet exist). The code below may be helpful in this scenario:

const arr1 = [{"OwnershipNumber": 0,"ID": null,"Name": "Contractor LLC","ContrEmployeeTypeId": 0,"ContactEmail": "","ContactPhone": "","VeteranEmployeeMilitaryAffiliation": "","SocialSecurityNumber": "","DrivingLicense": "","DateOfBirth": null,"OwnershipPercentage": 0,"IsContractorActive": "Y","VeteranFlag": "N","VeteranEmployeeHireDate": null,"LegalIssueFlag": "N","ActiveFlag": true,"TimeStamp": null},{"OwnershipNumber": 1878,"ID": null,"Name": "Greg Dawson","ContrEmployeeTypeId": 2,"ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89f9fbe8c9e8ebeaa7eae6e4">[email protected]</a>","ContactPhone": "455-455-6444","VeteranEmployeeMilitaryAffiliation": null,"SocialSecurityNumber": "454534245","DrivingLicense": "44524245","DateOfBirth": "11/30/1968 12:00:00 AM","OwnershipPercentage": 100,"IsContractorActive": "Y","VeteranFlag": "N","VeteranEmployeeHireDate": null,"LegalIssueFlag": "N","ActiveFlag": true,"TimeStamp": null}];
const arr2 = [ {"OwnershipNumber": 1878, "ContactPhone": "111-222-6444"},{"OwnershipNumber": null,"ID": 3,"SocialSecurityNumber": "465464654","DrivingLicense": "464654654654","DateOfBirth": "1998-12-12T18:30:00.000Z","VeteranEmployeeHireDate": "1970-01-01T00:00:00.000Z","Name": "Tom Hanks","ContrEmployeeTypeId": 1,"IsContractor": "N","ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a5e45476a4d474b434604494547">[email protected]</a>","ContactPhone": "564-465-4654","OwnershipPercentage": 100}];
arr2.forEach(t => {
  for(const [idx, obj] of arr1.entries()){
    if(obj.OwnershipNumber === t.OwnershipNumber) {
      // The object exists in arr1, so we need to update the existing object
      arr1[idx] = {...arr1[idx], ...t};
      return;
    }
  }
  // The object does not already exist, so we should add it to the array
  arr1.push(t);
});
console.log(arr1);

Answer №2

To effectively organize your data, it is essential to have a specific identifier. In this case, I believe the key could be named OwnershipNumber. Moving forward to address this issue, we can utilize the reduce() function to group the data:

const arr1 = [{"OwnershipNumber": 0,"ID": null,"Name": "Contractor LLC","ContrEmployeeTypeId": 0,"ContactEmail": "","ContactPhone": "","VeteranEmployeeMilitaryAffiliation": "","SocialSecurityNumber": "","DrivingLicense": "","DateOfBirth": null,"OwnershipPercentage": 0,"IsContractorActive": "Y","VeteranFlag": "N","VeteranEmployeeHireDate": null,"LegalIssueFlag": "N","ActiveFlag": true,"TimeStamp": null},{"OwnershipNumber": 1878,"ID": null,"Name": "Greg Dawson","ContrEmployeeTypeId": 2,"ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0a0a2b190b1b2b3feb3bfbd">[email protected]</a>","ContactPhone": "455-455-6444","VeteranEmployeeMilitaryAffiliation": null,"SocialSecurityNumber": "454534245","DrivingLicense": "44524245","DateOfBirth": "11/30/1968 12:00:00 AM","OwnershipPercentage": 100,"IsContractorActive": "Y","VeteranFlag": "N","VeteranEmployeeHireDate": null,"LegalIssueFlag": "N","ActiveFlag": true,"TimeStamp": null}];
const arr2 = [ {"OwnershipNumber": 1878, "ContactPhone": "111-222-6444"},{"OwnershipNumber": null,"ID": 3,"SocialSecurityNumber": "465464654","DrivingLicense": "464654654654","DateOfBirth": "1998-12-12T18:30:00.000Z","VeteranEmployeeHireDate": "1970-01-01T00:00:00.000Z","Name": "Tom Hanks","ContrEmployeeTypeId": 1,"IsContractor": "N","ContactEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dda9b2b09dbab0bcb4b1f3beb2b0">[email protected]</a>","ContactPhone": "564-465-4654","OwnershipPercentage": 100}];

var result = Object.values([...arr1, ...arr2].reduce((acc, {OwnershipNumber, ...rest})=>(
   acc[OwnershipNumber] = {...(acc[OwnershipNumber] || {}), ...{OwnershipNumber, ...rest}},
   acc
),{}));

console.log(result);

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

Is it possible to have a leaderboard stored in a database without requiring user

I am in the process of developing a game using Javascript that includes a leaderboard feature. Originally, my plan was to allow players to enter their name and then click a button to start the game. Since the game includes a countdown timer, I needed a w ...

Innovative approach to accessing structures in C

I have a unique project that requires the development of a C program for specialized software utilized within my company. My goal is to optimize the program for efficiency, but I have encountered an unusual challenge with how the software handles the signa ...

Angular applications hosted on .Net Core should include a robots.txt file to provide instructions to web

I am currently running a web application on a Windows server, built with Angular 5 for server side rendering and hosted within .Net Core. I recently uploaded a robots.txt file to the root directory of the server, but when attempting to access it via , the ...

The object filtering process is experiencing issues due to the presence of a null value in the column

I am trying to extract object data based on a specific value from an array. While the code snippet below works well when there are no null values, it fails to work properly when encountering null values in the column. For reference, you can check out this ...

Current target in Internet Explorer 10 with Javascript

Encountering a problem with event.currentTarget in IE 10. Two divs are present on the website. The first div contains an image that takes up the entire screen, while the second div is smaller and positioned over the first div. The smaller div has no conte ...

Validating Angular input for decimal values based on specific criteria

Is there a way to limit user input to numbers with only 2 decimal places if both itemNew.UL_DATA and itemNew.LL_DATA are equal to 0 or blank? <ion-col col-2> <input (keypress)="ShowKey();" [style.display]="itemNew.UL_DATA== ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

complete() method is not triggered by Observable

Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables. In my Angular application, I have developed a timer with a start button, a ...

Put emphasis on the input field - React component

My React component features an input field with a disabled attribute. When the component is clicked, the input becomes enabled for the user to type in. I have successfully implemented this functionality so far, but now I need to focus on the input field on ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

Ways to examine a JavaScript Bound Function

Can a JavaScript bound function be inspected somehow? I need to be able to return a bound function from a function, and when unit testing, I'd like to verify the bound function's target, boundThis, and boundArgs. These properties seem to be inte ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Navigate the div with arrow keys

Looking for an answer similar to this SO post on moving a div with arrow keys, could a simple and clear 'no' be sufficient: Is it possible to turn an overflowing div into a "default scroll target" that responds to arrow-up/down/page-down/space k ...

What could be the reason behind the ajax call not getting triggered?

Upon page load, the first alert is displaying correctly. However, the alert inside the ajax call is not triggering. It appears that the ajax call itself is not functioning as intended - it is supposed to invoke a method in the controller, but no longer s ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Navigating the intricacies of platform-specific settings in JavaScript

Currently, I am in the process of transferring an application from one PHP-based CMS to another (such as Wordpress, Joomla, etc.). I have established classes that enable my code to function seamlessly on each platform without any alterations (so far so goo ...

Find the matching ID and consolidate all the information under one single ID

I am looking to merge objects with the same title and consolidate their data into a single object. new = [{ "data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon"}], "title&quo ...

The default selection for React Material Multiselect items is not being chosen

Currently, I am working on implementing the React Material autocomplete component that includes a multiple-values checkbox. However, it seems like there is an issue with the defaultValue prop and the checkboxes example. Even though I set defaultValue to a ...

Utilize lodash to eliminate items from an array within an array

I am looking to eliminate users from the removeUser array based on their userName values using lodash. Here is the data I have: {"users":[ {"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_e ...