我有 4 个独立的对象数组,有没有一种方法可以根据对象内部的键将它们全部连接到一个大对象中。
这是一个例子 输出:我想要实现的目标。
[
{
"bugId": "",
"testerId": "",
"firstName": "",
"lastName": "",
"country": "",
"deviceId":"",
"description":""
}
]
<小时/>
测试人员对象
(超过500个)
[
{
"testerId":"1",
"firstName":"John",
"lastName":"Doe",
"country":"US",
}
]
bugId
的对象(这应该是我们能够获取输出的主要对象)
由于 deviceId
连接到 description
,testerId
连接到 firstName
、lastName
和国家
。
[
{
"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"
}
]
设备对象
[
{
"deviceId":"1",
"description":"iPhone 4"
}
]
最佳答案
将测试仪和设备收集到单独的 Maps 中使用Array#reduce 。 使用 Array#map 迭代 bugs 数组,并使用 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);
关于javascript - javascript中根据key合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385036/