Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda