Создать один массив из двух, где в массиве album есть userId и есть массив пользователей с уникальным id
Создать один массив из двух, где в массиве album есть userId и есть массив пользователей с уникальным id.
const arrayOfAlbums = [
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
},
{
"userId": 1,
"id": 2,
"title": "sunt qui excepturi placeat culpa"
},
{
"userId": 1,
"id": 3,
"title": "omnis laborum odio"
},
]
const arrayOfUsers = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
},
{
"id": 2,
"name": "Lamer Pajam",
"username": "Alex",
"email": "[email protected]",
},
]
const mergedArrShouldBe = [
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim",
"author": "Lamer Pajam",
},
{
"userId": 1,
"id": 2,
"title": "sunt qui excepturi placeat culpa",
"author": "Lamer Pajam"
},
{
"userId": 1,
"id": 3,
"title": "omnis laborum odio",
"author": "Lamer Pajam"
},
]
Ответы (1 шт):
Автор решения: Mark Mor
→ Ссылка
Best way to do this it's a tricky one cuz id of user override id of album so i decide to create a new obj without id [just a name] and merge it wiht album
const mergedArray = arrayOfAlums.data.reduce((acc, album) => {
arrayOfUsers.data.map(user => {
if (user.id === album.userId) {
const userWithoutId = {author: user.name}
acc.push({...album, ...userWithoutId})
}
return user
})
return acc
},[])
Not good way
const mergedArray = arrayOfAlums.map(album => ({...album, ...arrayOfAuthors.find(author => author.id === album.userId)}))
