0

Say I have two data arrays for a ticketed event. One is attendees:

[
{name: 'Jack', ticket_code: 'iGh4rT'},
{name: 'Lisa', ticket_code: 'it1ErB'}
]

The other is tickets:

[
{code: 'iGh4rT', name: 'General Admission'},
{code: 'it1ErB', name: 'VIP'}
]

Now say I want to display a table like this:

Name Ticket Name
Jack General Admission
Lisa VIP

I am struggling with doing this efficiently. I can display a table with one array no problem like something like this:

    for (let i = 0; i < attendees.length; i++){
        const row = `<tr>
                        <td>${attendees[i].name}</td>
                        <td>${attendees[i].ticket_code}</td>
                    </tr>`
    document.getElementById('TableBody').innerHTML += row

I need to somehow 'query' the tickets array with the code from the attendees array for that particular person, get the name of the ticket, and supplant the ticket name instead of the code.

With SQL something like this is easy, but is one able to "query" an array and get a specific property? Should I construct a whole new array with the needed info? What is the best way to do this that would work for large unordered datasets?

The_Don
  • 5
  • 3
  • You can use objects (hash tables in general) where the key is `ticket_code` or `code`. The value can be name. Then, searching should be easier since you need to do just this `ticketsObj[code]` to get a name. – arfat Jun 17 '21 at 05:43

2 Answers2

1

You could take one of your array as an object with code as key for the object and map the other array with wanted data and the previous stored data from the object.

const
    attendees = [{ name: 'Jack', ticket_code: 'iGh4rT' }, { name: 'Lisa', ticket_code: 'it1ErB' }],
    tickets = [{ code: 'iGh4rT', name: 'General Admission' }, { code: 'it1ErB', name: 'VIP' }],
    ticketsByCode = Object.fromEntries(tickets.map(o => [o.code, o])),
    table = attendees.map(({ name, ticket_code }) => [name, ticketsByCode [ticket_code].name]);

console.log(table);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

try this:

let a = [
  {name: 'Jack', ticket_code: 'iGh4rT'},
  {name: 'Lisa', ticket_code: 'it1ErB'}
];

let b = [
  {code: 'iGh4rT', name: 'General Admission'},
  {code: 'it1ErB', name: 'VIP'}
];

let c = b.map(item => {
    return {
        tiketName: item.name,
        ...a.find(itemA => itemA.ticket_code == item.code)
    }
});

console.log(c);
Bahador Raghibizadeh
  • 1,155
  • 11
  • 23