I have a data array:
[
{ name: '1', goalsTable: 6544b8a5fea0bf50fc0c62fb },
{ name: '1fork', goalsTable: 6548740f05dc440b5c61c5ac }
]
I have a goalsData array:
[
{
_id: 6544b8a5fea0bf50fc0c62fb,
tableData: [ [Object], [Object], [Object], [Object] ],
goalsData: { qty: 12 }
},
{
_id: 6548740f05dc440b5c61c5ac,
tableData: [ [Object], [Object], [Object], [Object], [Object] ],
goalsData: { qty: 10 }
}
]
What I want is to merge the object if the id matches with each other. Like for example, if _id of first object of goalsData matches with the goalsTable of data, then the data object becomes:
[{
name: '1',
goalsTable: 6544b8a5fea0bf50fc0c62fb,
tableData: [ [Object], [Object], [Object], [Object] ],
goalsData: { qty: 12 }
}]
3
Answers
The objective can be achieved easily if you convert the second array into a lookup object:
Using a lookup object requires more memory but it will speed up the matching process. This becomes more important for large arrays.
If I understand you correctly you are trying to match the _id of one array with the goalstable key of the other array. To do this You might want to loop over both arrays. I used the .map function to loop over both arrays in a nested form and with an if statement I checked whether the latter values matched, if so, I added the values to the initial array.
Tested the result in the following snippet and they are working fine.
Wit
lodash
we can handle your case like this one. You can implementomit
by yourself but I think it’s more convenient because most of JS project will uselodash
.