I am trying to output a string like "Team 1 has the following employees: Joe, Mark, and John. Team 2 has the following employees: Lauren, Conrad, and Sumeet." I have the following object:
const teamInfo = {
teams: {
team1: ['Joe', 'Mark', 'John'],
team2: ['Lauren', 'Conrad', 'Batman'],
},
}
I have tried the following, which produces somethign that looks sort of like what I want but since the output contains objects, I cannot customize the section of the output that lists the names. For example, I cannot have it say "Team1 includes Joe, Mark, AND John. And team2 includes, Lauren, Conrad, and Batman."
let infoString = "";
for (const [team, employees] of Object.entries(teamInfo.teams)) {
infoString += ` ${team} employees include: ${employees}. `;
}
console.log(infoString)
How do I accomplish this without using any quick or more intermediate/advanced methods? I basically want to be able to do it with basic JS using loops, Object.entries/keys/values rather than quick shortcuts.
I have also tried various permutations of looping over the employees array and nesting another loop within it but that has obvious issues. Another attempt came close, but it outputted three times, rather than all at once.
Not looking for just a solution; but some advice.
THank you
Inside the for loop, you can create a copy of the employees without the last item, join it by a comma, then concatenate 'and' and the last employee name:
const teamInfo = {
teams: {
team1: ['Joe', 'Mark', 'John'],
team2: ['Lauren', 'Conrad', 'Batman'],
},
}
let infoString = "";
for (const [team, employees] of Object.entries(teamInfo.teams)) {
infoString += ` ${team} employees include: ${employees.slice(0, -1).join(', ')} and ${employees[employees.length - 1]}\n`;
}
console.log(infoString)