I have the following array which is assumed to be large data set.
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] ] }
];
I have another array which i got as a result of database query (which is also a large data set)
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"
}
];
I need to add the attributes such as dob, name from dbResponse to response1 array based on same userID. All the userID in response1 array should be populated with attributes like dob, name from dbResponse. I am confused on how to perform the below in large data set.
Expected output will be like this:
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' }
];
What will be the best way to achieve this using es6 functions for a large data sets? I am new to these es6 functions. Any help would be really appreciated.
Iterate dbResponse
for every userId
in response1
, extract the object and copy the object in response1
.
As both are large arrays, you will have to iterate dbResponse
a large number of times. To optimize the operation of finding the response1
corresponding userID
object in the dbResponse
array, you could maintain a mapping to reduce the searching complexity.
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;
}, []);
The final result will be in finalResult
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다