【问题标题】:Merge objects based on key in javascript基于javascript中的键合并对象
【发布时间】:2018-05-03 06:14:51
【问题描述】:

我有 4 个单独的对象数组,有没有办法根据对象内的键将它们全部连接成一个大对象。

这是一个例子 输出:我想要达到的目标。

[
{
    "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,提供1台测试仪4台设备

[  
   {  
      "testerId":"1",
      "deviceId":"1"
   },
   {  
      "testerId":"1",
      "deviceId":"2"
   },
   {  
      "testerId":"1",
      "deviceId":"3"
   },
   {  
      "testerId":"1",
      "deviceId":"10"
   }
]

devices的对象

[  
   {  
      "deviceId":"1",
      "description":"iPhone 4"
   }
]

我搜索了Lodash Library,但 here 提到,对于同名的键,无法合并。我应该采取什么方法?

【问题讨论】:

  • 您可以使用 Lodash 的 _.keyBy 将您的 testers 和 devices 数组转换为对象,并由它们各自的 ID 键入。然后你可以迭代你的 bugs 数组并建立相关数据
  • tester_devices 应该如何参与其中?它是否相关?
  • tester_devices,可以避免。由于必须根据设备名称进行搜索,我可以将其替换为数字,即deviceId。

标签: javascript json ecmascript-6 lodash


【解决方案1】:

使用Array#reduce 将测试人员和设备收集到单独的Maps 中。 使用Array#map 迭代bugs 数组,并使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2018-12-29
    • 2022-12-18
    • 2018-04-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多