Combining items in JavaScript using a shared key

Is there a way to combine 4 separate arrays of objects into one big object based on the keys inside an object?

For example: OUTPUT: What I want to achieve.

[
{
    "bugId": "",
    "testerId": "",
    "firstName": "",
    "lastName": "",
    "country": "",
    "deviceId":"",
    "description":""
}
]

An array of testers (over 500 entries)

[  
   {  
      "testerId":"1",
      "firstName":"John",
      "lastName":"Doe",
      "country":"US",
   }
]

An array for bugId (the main object for getting the output) Since deviceId is linked to description and testerId is linked to firstName, lastName and Country.

[  
   {  
      "bugId":"1",
      "deviceId":"1",
      "testerId":"1"
   }
]

An array for tester_devices, where each tester has 4 devices

[  
   {  
      "testerId":"1",
      "deviceId":"1"
   },
   {  
      "testerId":"1",
      "deviceId":"2"
   },
   {  
      "testerId":"1",
      "deviceId":"3"
   },
   {  
      "testerId":"1",
      "deviceId":"10"
   }
]

An array of devices

[  
   {  
      "deviceId":"1",
      "description":"iPhone 4"
   }
]

I looked into the Lodash Library, but found that merging objects with the same key names may be problematic. What approach should I consider?

Answer №1

Separate the testers and devices into distinct Maps by utilizing Array#reduce. Loop through the bugs array using Array#map, then merge objects from both Maps based on their ids with Object#assign:

const testers = [{"testerId":"1","firstName":"John","lastName":"Doe","country":"US"}];
const bugs = [{"bugId":"1","deviceId":"1","testerId":"1"}];
const devices = [{"deviceId":"1","description":"iPhone 4"}];

const createMap = (arr, key) => arr.reduce((m, o) => m.set(o[key], o), new Map());

const testersMap = createMap(testers, 'testerId');
const devicesMap = createMap(devices, 'deviceId');

const merged = bugs.map(({ bugId, testerId, deviceId }) => Object.assign({ bugId }, testersMap.get(testerId), devicesMap.get(deviceId)));

console.log(merged);

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

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}'). But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is a ...

Send an ArrayList to jQuery Flot

Good day. Apologies for any language barriers as English is not my first language. I am a novice in [see tags] and I have a web application that gathers a date and a serial number to execute a SQL query. The query returns some data (measurement values an ...

Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section. <Collapse defaultActiveKey={["1"]} expandIconPosition="right" > <Panel header="This is p ...

The Math.random() function is responsible for producing a single random number

I have a unique idea for a keyboard that generates divs when keys are pressed. The keyboard functionality has already been implemented. Each div should be positioned randomly on the screen but still be grouped by letter. My approach involves adding a rando ...

Encountering a JSON encoding problem while trying to upload a large amount of data into ElasticSearch, specifically limited

When I upload a file to the ElasticSearch /_bulk api for inserting or updating records, I encounter an issue. Interestingly, when I perform this task from my local machine (running OSX), everything works smoothly and there are no problems with sending data ...

Having trouble updating state in React after making a fetch request

I am encountering an issue with setting the current user after a successful login. Even though the login process is successful and the data is accurate, I am unable to set the state as the user data appears to be empty. UserContext.js import React, { useC ...

Modify only the visual appearance of a specific element that incorporates the imported style?

In one of my defined less files, I have the following code: //style.less .ant-modal-close-x { visibility: collapse; } Within a component class, I am using this less file like this: //testclass.tsx import './style.less'; class ReactComp{ re ...

How to store selected checkbox values in an array using AngularJS

Check out this code snippet: <tr ng-repeat="doc in providers"> <td><input type="checkbox" ng-true-value="{{doc.provider.Id}}" ng-false-value="" ng-model="ids"></td> </tr> {{ids}} I am trying to store the values of ...

DataGrid Component: Implementing a Button for Deleting Rows

I am currently developing a React component with MaterialUI, incorporating a Datagrid to manage a queue of files. The layout resembles this: https://i.sstatic.net/oh0GH.png One functionality I'm focusing on is when the user clicks on the three dots a ...

Can you explain how to use a toggle switch to make a select dropdown select a random option?

Currently, I am in the process of setting up a page for a character generator. Users will have the option to randomize traits or input their own. The interface includes toggle switches for the "choice vs random" options for each trait category, as well as ...

Setting character limits within textareas based on CSS classes in a dynamic manner

I'm looking to develop a JavaScript function that can set text limits for multiple textareas at once using a class, allowing for flexibility in case specific textareas need to be exempt. However, I'm facing issues with my debuggers - Visual Studi ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

Which event listener in the DOM API should I use to trigger an action when a form field is focused, whether through a mouse click or by tabbing?

My aim is to increase the size of form fields when the cursor focuses on them, either through a mouse click or by tabbing using the keyboard. By utilizing document.activeElement focus, I can identify when the user clicks inside a text input or selects an ...

What is causing the malfunction in angular-debounce in version 1.3.0?

Take a look at this demo: http://jsfiddle.net/9sqtvcou/1/ If you enter something in the input and then wait 500ms, you'll notice that changing the "external resources" to version 1.2.27 (latest v1.2 as of the date I posted this) makes it work, other ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Using React Router useHistory to navigate to different routes programmatically

Currently, I'm working on creating a wizard interface and running into some issues with the buttons. Right now, I have next and back buttons for each route, but I am aiming to create a button component that can handle navigation both forward and backw ...

Navigating React Router: Updating the page on back button press

Looking for a solution to a persistent issue. Despite various attempts and exhaustive research, the problem remains unresolved. Here's the situation: Within my React-Router-Dom setup, there is a parent component featuring a logo that remains fixed an ...