0

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?

Phil
  • 157,677
  • 23
  • 242
  • 245
hemantmetal
  • 107
  • 10
  • You could just use Lodash's [`_.keyBy`](https://lodash.com/docs/4.17.4#keyBy) to convert your `testers` and `devices` arrays into objects, keyed by their respective IDs. Then you can just iterate your `bugs` array and build up the related data – Phil Nov 20 '17 at 04:27
  • How should `tester_devices` play into this? Is it relevant at all? – Phil Nov 20 '17 at 04:27
  • `tester_devices`, it can be avoided. As have to search based on the device name, which I can substitute with the number i.e `deviceId`. – hemantmetal Nov 20 '17 at 04:29

1 Answers1

3

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209