Can we combine two arrays of objects based on their unique identifiers?

I am working with two arrays of objects:

firstAry = [{
    "status": "Creating",
    "datacenter-id": "1test",
    "datacenter-name": "1name"
}, {
    "status": "Creating",
    "datacenter-id": "2test",
    "datacenter-name": "2name"
}, {
    "status": "Creating",
    "datacenter-id": "id1"&,
    "datacenter-name": "data6"
}, {
    "status": "Creating",
    "datacenter-id": "id2",
    "datacenter-name": "data7"
}]
secondAry = [
  {
    "status": "Creating",
    "cluster-id": "1test",
    "cluster-name": "clu1",
    "datacenter-id": "null"
  },
  {
    "status": "Creating",
    "cluster-id": "1test1",
    "cluster-name": "clu1",
    "datacenter-id": "id1"
  },
  {
    "status": "Creating",
    "cluster-id": "1test113",
    "cluster-name": "clu11",
    "datacenter-id": "id1"
  },
  {
    "status": "Creating",
    "cluster-id": "2test2",
    "cluster-name": "clu2",
    "datacenter-id": "id2"
  },
  {
    "status": "Creating",
    "cluster-id": "2test22",
    "cluster-name": "clu22",
    "datacenter-id": "id2"
  }
]

I am looking to create a table with the following fields: status, cluster-name, and datacenter-name. However, the datacenter-name is split between the two arrays, and I need to merge them based on the datacenter-id. If there is no matching datacenter-id, then the datacenter-name field should be blank. I want to extract the datacenter-name from the firstAry array and add it to the corresponding object in the secondAry array.

The resulting array of objects should be structured like this:

Result = [   
{     "status": "Creating",     "cluster-id": "1test",     "cluster-name": "clu1",     "datacenter-id": "null" ,"datacenter-name": "null"  },   
{     "status": "Creating",     "cluster-id": "1test1",     "cluster-name": "clu1",     "datacenter-id": "id1", "datacenter-name": "data6"    },   
{     "status": "Creating",     "cluster-id": "1test113",     "cluster-name": "clu11",     "datacenter-id": "id1" , "datacenter-name": "data6"   },   
{     "status": "Creating",     "cluster-id": "2test2",     "cluster-name": "clu2",     "datacenter-id": "id2" ,"datacenter-name": "data7" },   
{     "status": "Creating",     "cluster-id": "2test22",     "cluster-name": "clu22",     "datacenter-id": "id2"  ,"datacenter-name": "data7" } ]

I have attempted to use the filter method, but it is removing elements with no matching id. Can you please assist in achieving this?

Answer №1

forEveryElementInSecondArray(x=>{
   matchDataInFirstArray=dataBeingSearchedInFirstArray.find(f=>f['datacenter-id']==x['datacenter-id'])
   x['datacenter-name']=matchDataInFirstArray?matchDataInFirstArray['datacenter-name']:''
})

NOTE: I strongly recommend using camelCase notation before resorting to using a "-". If you have to use a "-", you will need to access the property using obj['property'], otherwise it's simply obj.property

Answer №2

Locate and update matching elements in one array by comparing it to another array. Adjust the output and output a new array with modifications.

const updatedArray = secondArray.map(element => {
const queriedElement = firstArray.find(fElement => fElement['datacenter-id'] === 
element['datacenter-id'] );
if(queriedElement && Object.keys(queriedElement).length > 0 ){
  element['datacenter-name'] = queriedElement['datacenter-name']
}else{
   element['datacenter-name'] = 'null'
}
 return element;
});

console.log(updatedArray);

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 efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

What is the process for transforming an AJAX request's onreadystatechange into a promise?

During the process of making a javascript AJAX request, I initially utilized the traditional callback approach to call the callback function within the onreadystatechange and retrieve all the values of readyState. However, upon switching my callback funct ...

Sending Node.js FileStream Image to HTML5 FileReader API

Is there a way to utilize Node FileSystem for opening a file and then having it read by the FileReader API? const myFile = "C:\\Users\\Me\\Image.png"; fs.readFile(myFile, (error, data) => { const blob = new B ...

Substitute the division

Can I make the old div change its position and move to the side when I add a new div? And can all the old divs be hidden when adding four new divs? This is for my full news website and I want this applied to all four pages. First page: https://i.sstatic. ...

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

the level of zoom in my Angular application automatically goes up when it's in production mode

I have encountered an issue with my Angular application where it appears very zoomed in when hosted on a Node JS server, despite running correctly under the Angular development server. This zoomed-in view is beneficial for readability but ruins the overall ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

How many server queries does a single web application require?

As someone new to web app development, my main goal is to optimize speed as much as possible. I am faced with two options: The first option is to fetch data from the database individually every time a refresh is needed in the app. Alternatively, I c ...

What is the best way to transfer the "user" object from TopBar.js to App.js in my project?

In my project, TopBar.js functions as an AppBar component responsible for handling user authentication. When a user logs in, I receive an object called "user". My goal is to export this "user" object to App.js. If I am successful in exporting it to App.js ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Update the parent node in the Google Org Chart

This is my first time working with Google Charts and I have a couple of questions: Is there a method in the API to update the parent of an existing node? I am facing a challenge where I need to build a tree structure top-down, which means that I know the ...

Utilizing multiple parameters as variables in Angular's router

Here is an example of how my router configuration will be set up: { path: ':firstVariable', component: FirstComponent }, { path: ':secondVariable', component: Secon ...

Is the canActivate function causing a lag in the application? When is the appropriate time to invoke it?

I have an Angular application with a .NET Core backend. User authorization and identification are handled through Windows Active Directory. While everything is functional, I suspect that the app may be running slowly. Upon investigation, it seems that the ...

Can I deactivate JavaScript on my website directly from my server settings?

I'm currently attempting to link my Android application to a PHP script hosted on a free server. However, when my app tries to access the page, I receive an HTML message stating that JavaScript is disabled and needs to be enabled in order to view the ...

Retrieving values using the jQuery .each() function and passing them to an AJAX request

Is it possible to set jQuery AJAX outside of .each in the script provided below? $('#btnUpdate').click(function() { $('#result').html(''); $('.moduleIDInput').each(function() { var uid = $(this). ...

Retrieving width and height of the content block inner in Framework7, excluding navbar and toolbar dimensions

Is there a reliable way to determine the width and height of the page content-block-inner, excluding the navbar and toolbar? This measurement can vary across different devices and operating systems. I attempted to assign an id to the content-block-inner a ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...