[英]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. 我有4个单独的对象数组,有没有一种方法可以根据一个对象内部的键将所有这些对象合并为一个大对象。
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) testers
对象(超过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
对象(这应该是我们可以从中获取输出的主要对象)由于deviceId
连接到description
而testerId
连接到firstName
, lastName
和Country
。
[
{
"bugId":"1",
"deviceId":"1",
"testerId":"1"
}
]
Object for tester_devices
, one tester is provided 4 devices tester_devices
对象,为一名测试人员提供4个设备
[
{
"testerId":"1",
"deviceId":"1"
},
{
"testerId":"1",
"deviceId":"2"
},
{
"testerId":"1",
"deviceId":"3"
},
{
"testerId":"1",
"deviceId":"10"
}
]
Object of devices
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. 我搜索了Lodash库,但是这里提到对于具有相同名称的键,无法合并。 What approach should I take?
我应该采取什么方法?
Collect the testers, and the devices into separate Maps using Array#reduce . 使用Array#reduce将测试人员和设备收集到单独的Map中 。 Iterate the bugs array with Array#map , and combine objects from both Maps by their ids using Object#assign :
使用Array#map迭代bug数组,并使用Object#assign通过两个ID组合两个Map中的对象 :
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.