Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
How to display all values from variable

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
});
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!