I'm drawing data from a database and ending up with an array of objects each containing waiter names and the the days they have worked. I want to dynamically restructure the array by condensing it to a single object with two property value pairs per waiter. One property for the name and another for the days working.
I am really curious to see your feedback. I started off by extracting the names and removing duplicates. Leaving me with an array like this: let waiterNames = ['John','Mark','Jess'].
Then I was attempting a double for of loop and somehow creating a new array of objects, but I'm stuck.
for (entry in waiterInfo) {
for (waiter in waiterNames) {
if (entry.waiters == waiter) {
???
}
}
}
waiterInfo is what I start with, newInfo is what I want to achieve. I need this to happen dynamically because the data drawn from the database is unpredictable.
let waiterInfo = [{ waiters: 'John', weekdays: 'Monday' },
{ waiters: 'John', weekdays: 'Tuesday' },
{ waiters: 'John', weekdays: 'Wednesday' },
{ waiters: 'Mark', weekdays: 'Monday' },
{ waiters: 'Mark', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Monday' },
{ waiters: 'Jess', weekdays: 'Tuesday' },
{ waiters: 'Jess', weekdays: 'Wednesday' },
{ waiters: 'Jess', weekdays: 'Thursday' }]
let newInfo = [{ waiters: 'John', weekdays: 'Monday, Tuesday, Wednesday'},
{ waiters: 'Mark', weekdays: 'Monday, Tuesday' },
{ waiters: 'Jess', weekdays: 'Monday, Tuesday, Wednesday, Thursday' }]
select waiter_username as waiters, weekdays_working as weekdays from waiters order by waiter_username;select waiter_username, array_agg(weekdays_working) as weekdays from waiters group by waiter_usernameshould do the trick.