我有以下数组,假定它是大型数据集。
let response1 = [
{ userID: '2222', dataOne: [ [Object], [Object] ] },
{
userID: '6666',
dataOne: [ [Object] ],
dataTwo: [ [Object], [Object] ]
},
{
userID: '11111',
dataOne: [ [Object], [Object] ],
dataTwo: [ [Object] ]
},
{ userID: '4586', dataTwo: [ [Object] ] }
];
我有另一个数组,这是数据库查询的结果(这也是一个大数据集)
let dbResponse = [{
"attributes": {
"dob": "19890147",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Ketan Hol",
},
"doctorID": "ds45ds",
"userID": "11111"
},
{
"attributes": {
"dob": "19890386",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Sachin",
},
"doctorID": "erjjkrel",
"userID": "6666"
},
{
"attributes": {
"dob": "19890219",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Vishwas",
},
"doctorID": "dfgfdg",
"userID": "2222"
},
{
"attributes": {
"dob": "19890219",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Jis",
},
"doctorID": "dfgfdg",
"userID": "98645"
},
{
"attributes": {
"dob": "19890219",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Brad",
},
"doctorID": "dfgfdg",
"userID": "4586"
},
{
"attributes": {
"dob": "19890219",
"gender": "M",
"mobilePhone": "1239000000",
"name": "Brad",
},
"doctorID": "dfgfdg",
"userID": "4586"
}
];
我需要根据相同的用户ID将dbResponse中的dob、name等属性添加到response1数组中。 response1 数组中的所有 userID 都应使用 dbResponse 中的 dob、name 等属性进行填充。我对如何在大数据集中执行以下操作感到困惑。
预期输出如下:
response1 = [
{ userID: '2222', dataOne: [ [Object], [Object] ], dob: '19890219', name: 'Vishwas' },
{
userID: '6666',
dataOne: [ [Object] ],
dataTwo: [ [Object], [Object] ],
dob: '19890386',
name: 'Sachin'
},
{
userID: '11111',
dataOne: [ [Object], [Object] ],
dataTwo: [ [Object] ],
dob: '19890147',
name: 'Ketan Hol'
},
{ userID: '4586', dataTwo: [ [Object] ], dob: '19890219', name: 'Brad' }
];
对于大型数据集使用 es6 函数实现此目的的最佳方法是什么?我对这些 es6 功能很陌生。任何帮助将不胜感激。
最佳答案
方法1
针对response1
中的每个userId
迭代dbResponse
,提取对象并复制response1
中的对象。
方法2(优化操作)
由于两者都是大型数组,因此您必须迭代dbResponse
很多次。为了优化在 dbResponse
数组中查找 response1
对应的 userID
对象的操作,您可以维护一个映射来降低搜索复杂度。
const result = dbResponse.reduce((acc, obj) => {
const { userID } = obj
acc[userID] = obj;
return acc;
}, {});
const finalResult = response1.reduce((acc, curr) => {
const { userID } = curr
const dbObj = result[userID] || {}
acc.push({
...curr,
...dbObj
})
return acc;
}, []);
最终结果将在finalResult
关于javascript - 使用来自不同数组的属性更新数组,并且两个数组具有相同的键 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63628199/