I am currently working on a project were I would like to assign specific song to a singer. The problem is that currently a singer can only be assigned one song. How can I check if the singer had already sung, and save the multiple songs into an array, and assign that array to the singer as a key/value pair?
const form = document.querySelector('form');
const songSpecialSinger = document.querySelector('#song-special-singer');
const songSpecialSong = document.querySelector('#song-special-song');
const songSingerList = {};
form.addEventListener('click', (e) => {
const target = e.target;
if (target.nodeName === 'BUTTON' && target.type === 'button' && (songSpecialSong.value != '')) {
if (songSingerList.hasOwnProperty(songSpecialSinger.value)) {
console.log('Singer already sang');
console.log(songSingerList[songSpecialSinger.value]);
}
songSingerList[songSpecialSinger.value] = songSpecialSong.value;
console.log(songSingerList);
songSpecialSong.value = ''
}
})
<form>
<div>
<label>Song Special:</label>
<select name="Song-special" id="song-special-singer"></select>
<input type="text" placeholder="Song" id="song-special-song">
<button class="add-song" type="button">add song</button>
</div>
<div class="button-container">
<button type="submit">generate post</button>
</div>
</form>
2
Answers
Create an array for each singer to store their songs.
Check if the singer already exists in the songSingerList object. If they do, you’ll add the new song to their existing array. If not, you’ll create a new array for that singer and add the song to it.
When submitting the form, you can iterate through the songSingerList object to generate the desired output.
Here is a version that adds an array to each singer and renders the object