Quiero combinar dos resultados json, pero me cuesta hacerlo.
primero ( galleryData ):
[
{ "userId": 2, "profile": { "profileImage": "image" } },
{ "userId": 4, "profile": { "profileImage": "image" } },
]
segundo ( combinations ):
{
data: [
{ round: 1, partner: 2 },
{ round: 2, partner: 4 }
]
}
la salida que estoy esperando:
{
data: [
{ round: 1, userId: 2, "profile": { "profileImage": "image" } },
{ round: 2, userId: 4, "profile": { "profileImage": "image" } }
]
}
Básicamente, necesito la imagen de profileImage de uno de mis resultados y asignarla a la identificación de usuario correcta
Lo que he intentado hasta ahora sin éxito:
let combinedResult = galleryData["userId"].map((item, i) => Object.assign({}, item, combinations[i]));
Puede usar map y en cada devolución de llamada use find para encontrar el ID de usuario correspondiente userId === partner
const galleryData = [
{ "userId": 2, "profile": { "profileImage": "image" } },
{ "userId": 4, "profile": { "profileImage": "image" } },
]
const combinations = {
data: [
{ round: 1, partner: 2 },
{ round: 2, partner: 4 }
]
}
let combinedResult = {
data: galleryData.map((item, i) => {
let combination = combinations.data.find(c => c.partner === item.userId);
return { ...item, round: combination.round }
})
};
console.log(combinedResult)
Creo que un poco intente usar Array.forEach y luego combine los Objetos
a = [
{ "userId": 2, "profile": { "profileImage": "image" } },
{ "userId": 4, "profile": { "profileImage": "image" } },
]
b = {
data: [
{ round: 1, partner: 2 },
{ round: 2, partner: 4 }
]
}
// inside forEach you can write the logic to get elements from array 'a' as you can use `find` to check which user is needed
b.data.forEach((i,e) => { b.data[e] = {...i, ...a[e]} })
console.log(b)
Espero que sea de ayuda.
let galleryData = [
{ "userId": 2, "profile": { "profileImage": "image" } },
{ "userId": 4, "profile": { "profileImage": "image" } },
];
let galleryDataAsUserId = {};
galleryData.forEach(elem=>{
galleryDataAsUserId[elem.userId] = elem;
})
let combinations = {
data: [
{ round: 1, partner: 2 },
{ round: 2, partner: 4 }
]
};
let data = combinations.data;
data.map(elem=>{
let newElem = elem;
newElem.profile = galleryDataAsUserId[elem.partner].profile;
});
console.log(data)