hemantmetal
hemantmetal

Reputation: 107

Merge objects based on key in javascript

I have 4 separate array of objects, is there a way to join all of them into one big object based on the keys inside an object.

Here is an example OUTPUT: what I want to achieve.

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

Object of testers(It's more than 500)

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

Object for bugId (This should be the main object from where we will be able to get the output) As deviceId is connected to description and testerId is connected to firstName, lastName and Country.

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

Object for tester_devices, one tester is provided 4 devices

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

Object of devices

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

I searched for Lodash Library, but here it's mentioned that for key with same name it's not possible to merge. What approach should I take?

Upvotes: 0

Views: 178

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Collect the testers, and the devices into separate Maps using Array#reduce. Iterate the bugs array with Array#map, and combine objects from both Maps by their ids using 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);

Upvotes: 3

Related Questions