I'm trying to filter these two arrays of objects by their id (id & userId).
I want to return only the title where id and userId are equals
Thank you !
const usersData = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
}
]
const albumsData = [
{
"userId": 1,
"id": 1,
"title": "FooBar"
},
{
"userId": 1,
"id": 2,
"title": "Trolololo"
},
{
"userId": 3,
"id": 3,
"title": "omnis laborum odio"
},
{
"userId": 4,
"id": 4,
"title": "non esse culpa molestiae omnis sed optio"
}
]
const results = usersData.map(({ id }) =>
albumsData.filter(({ userId }) => id === userId)
);
console.log(results);
Your code seems fine, but will return a nested array, so just use flatMap instead of map. And if you just want the title, just chain another .map to it:
const usersData = [{"id": 1,"name": "Leanne Graham","username": "Bret","email": "Sincere@april.biz",}];
const albumsData = [{"userId": 1,"id": 1,"title": "FooBar"},{"userId": 1,"id": 2,"title": "Trolololo"},{"userId": 3,"id": 3,"title": "omnis laborum odio"},{"userId": 4,"id": 4,"title": "non esse culpa molestiae omnis sed optio"}];
const results = usersData.flatMap(({ id }) =>
albumsData.filter(({ userId }) => id === userId)
).map(({title}) => title);
console.log(results);
const result = albumData.filter((data) => data.userId === usersData[0].id);
As has been pointed out, you'll get a nested array using map. But that might actually be desired if you add another item to the usersData array as you'll get the results grouped by index. If not, use flatMap with another map on the end to get the title.
const results = usersData.flatMap(({ id }) =>
albumsData.filter(({ userId }) => id === userId)
).map(entry=>entry.title)
Yields:
["FooBar","Trolololo"]