I was making another version of a music player and want to make some upgrades. I was about to write some code that creates all desired elements in a variable that will be used as a sort of database with song name, author and album
const elements = {
"song": {
"name": "songname",
"author": "songauthor",
"album": "songalbum"
}
};
so i copied a bit of code that I found on a website which creates div with a specified value
function addElement (element) {
var newDiv = document.createElement("div");
var newContent = document.createTextNode(`${element.name} ${element.author} ${element.album}`);
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
and after that i tried forEach function that should create all elements in "database"
elements.forEach(() => {
addElement(this)
})
and my problem is that it doesnt work when it comes to creating all the elements from variable
this does not change when you use an arrow function, so this is pointing to the caller of the parent function (or the window), not the array element inside the forEach.
If you want to use an arrow function, provide an argument for each array element to be passed to the arrow function.
elements is also an Object, not an Array, so you can't directly call .forEach on it. However, you can get each value stored in the object using Object.values and then subsequently call .forEach on that.
Object.values(elements).forEach(e => {
addElement(e);
});
You can't use forEach loop at Object, but you can try to convert your object to array using Object.values() or another object method.