I have a object that simulate a database relationships with multiple arrays and i want a sale that have a music genre (in this case, the sale with id: 1), but my code is returning all sales. I use the filter and map methods to simulate a select and join from SQL.
const db = {
events: [
{
id: "1",
name: "Rock in Rio 2020",
genre: "Music",
},
{
id: "2",
nome: "World Cup 2022",
genre: "Sport",
},
],
tickets: [
{
id: "1",
eventId: "1",
name: "Day 3",
description: "Music Concert",
},
{
id: "2",
eventId: "1",
name: "France x Brazil",
description: "Football Match",
},
],
sales: [
{
id: "1",
ticketId: "1",
value: "100",
},
{
id: "2",
ticketId: "2",
value: "200",
},
],
};
const musicSales = db.sales.filter((sale) => {
return db.tickets.map((ticket) => {
return db.events.map((event) => {
return (
sale.ticketId === ticket.id &&
event.id === ticket.eventId &&
event.genre === "Music"
);
});
});
});
console.log(musicSales);
Any idea how to fix this?
If your intention is to retrieve a list of sales which have tickets for Music events, you could simply use filter and avoid the mapping.
For example
const musicSales = db.sales.filter((sale) => {
const ticket = db.tickets[sale.ticketId];
const event = db.events[ticket.eventId];
return event.genre === "Music";
});
This filters the sales, looking up the ticket for each sale and the event for each ticket.
Note that this code assumes that every sale has a corresponding ticket and that every ticket has a corresponding event. If these assumptions don't hold, you'll need to add some if statements to check whether the tickets and events exist.
You could try either of the following:
const musicSales = db.events.filter(event => event.genre == 'Music').map(event => db.sales.find(sale => sale.id == event.id));
const musicSales = db.events.map(event => {
if(event.genre == 'Music'){
return db.sales.find(sale => sale.id == event.id);
}
});.filter(Boolean);
I think you're trying to get all sales corresponding to a ticket with event ID 1?
If that's the case, you can do:
const musicSales db.sales.filter(sale => sale.ticketId in db.tickets.filter(ticket => ticket.eventId === "1"));
The tickets filter callback returns true if the ticket has eventId equal to "1".
The sales filter callback returns true if the sale has ticketId within the result of the tickets filter.