Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display all values from variable

I was making another version of my music player and wanted like in version before make some upgrades, so i was about to create some kind of code that creates all elements in variable that is some kind of database with song name, author and album

const elements = {
  "song": {
    "name": "songname",
    "author": "songauthor",
    "album": "songalbum"
  },
  "song2": {
    "name": "songname",
    "author": "songauthor",
    "album": "songalbum"
  }
};

so i copied used code that is on website which creates div with my value that i specify

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 tryed forEach function that should create all elements in "database"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

elements.forEach(() => {
    addElement(this)
})

and my question is because it dont works how to create all elements from variable

>Solution :

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading