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?

3
  • You could just use Lodash's _.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 Commented Nov 20, 2017 at 4:27
  • How should tester_devices play into this? Is it relevant at all? Commented Nov 20, 2017 at 4: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. Commented Nov 20, 2017 at 4:29

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.