在javascript中基于键合并对象

时间:2017-11-20 04:21:16

标签: javascript json ecmascript-6 lodash

我有4个独立的对象数组,有没有办法根据对象内的键将所有对象连接成一个大对象。

这是一个例子 OUTPUT:我想要实现的目标。

[
{
    "bugId": "",
    "testerId": "",
    "firstName": "",
    "lastName": "",
    "country": "",
    "deviceId":"",
    "description":""
}
]

testers的对象(超过500)

[  
   {  
      "testerId":"1",
      "firstName":"John",
      "lastName":"Doe",
      "country":"US",
   }
]

bugId的对象(这应该是我们能够获得输出的主要对象) 由于deviceIddescription相关联,testerIdfirstNamelastNameCountry相关联。

[  
   {  
      "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"
   }
]

我搜索了Lodash库,但 here 提到,对于具有相同名称的密钥,无法合并。我应该采取什么方法?

1 个答案:

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