我有4个独立的对象数组,有没有办法根据对象内的键将所有对象连接成一个大对象。
这是一个例子 OUTPUT:我想要实现的目标。
[
{
"bugId": "",
"testerId": "",
"firstName": "",
"lastName": "",
"country": "",
"deviceId":"",
"description":""
}
]
testers
的对象(超过500)
[
{
"testerId":"1",
"firstName":"John",
"lastName":"Doe",
"country":"US",
}
]
bugId
的对象(这应该是我们能够获得输出的主要对象)
由于deviceId
与description
相关联,testerId
与firstName
,lastName
和Country
相关联。
[
{
"bugId":"1",
"deviceId":"1",
"testerId":"1"
}
]
tester_devices
的对象,一个测试人员提供4个设备
[
{
"testerId":"1",
"deviceId":"1"
},
{
"testerId":"1",
"deviceId":"2"
},
{
"testerId":"1",
"deviceId":"3"
},
{
"testerId":"1",
"deviceId":"10"
}
]
devices
的对象
[
{
"deviceId":"1",
"description":"iPhone 4"
}
]
答案 0 :(得分:3)
使用Maps将测试人员和设备收集到单独的Array#reduce中。 使用Array#map迭代错误数组,并使用Object#assign通过其ID合并两个地图中的对象:
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);