My React application receives an array consisting of one array which holds the ids of two others, and two arrays which contain the id and the name. I want to create one array, which holds the names which fit to the id from array one. Written in an censored form it looks like this:
There is array A, which consists of two ids and the own id (AAAAA_id).
A
{
"AAAAAA_id": "AA",
"BBBBBB_id": "BB",
"CCCCCC_id": "CC"
}
Than there is Array B which consists of BBBBBB_id and the name.
B
{
"BBBBBB_id": "BB",
"BBBBBB_name": "BName",
}
Furthermore there is Array C which consists of CCCCCC_id and the name
C
{
"CCCCCC_id": "CC",
"CCCCCC_name": "CName",
}
How can I achieve an new Array D which consists of
D
{
"AAAAAA_id": "AA",
"BBBBBB_id": "BB",
"BBBBBB_name": "BName",
"CCCCCC_id": "CC"
"CCCCCC_name": "CName",
}
Id did start with a combination of map and filter,
const D = A.map(x => {
But I don't know how to progress from here on to handle multiple arrays.
CodePudding user response:
You can use find
const D = A.map(a => ({
...a,
BBBBBB_name: B.find(b => b.BBBBBB_id == a.BBBBBB_id)?.BBBBBB_name,
CCCCCC_name: C.find(c => c.CCCCCC_id == a.CCCCCC_id)?.CCCCCC_name,
}))
or better performance solution
const MAP_ID_NAME_B = B.reduce((acc, cur) => {
acc[cur.BBBBBB_id] = cur.BBBBBB_name
return acc;
}, {})
const MAP_ID_NAME_C = C.reduce((acc, cur) => {
acc[cur.CCCCCC_id] = cur.CCCCCC_name
return acc;
}, {})
const D = A.map(a => ({
...a,
BBBBBB_name: MAP_ID_NAME_B[a.BBBBBB_id],
CCCCCC_name: MAP_ID_NAME_C[a.CCCCCC_id]
}));