Эта строка genre.textContent = item.name;
будет перезаписывать textContent
каждую итерацию forEach
, оставляя только последнее значение.
Вам нужно добавить к textContent
, используя +=
.
const genreArr = [
{id: 12, name: "Adventure"},
{id: 28, name: "Action"},
{id: 878, name: "Science Fiction"}
];
const genre = document.getElementById('genre');
genreArr.forEach(function(item){
genre.textContent += item.name + ' | ';
})
<div id="genre">
</div>
Альтернативный, более эффективный метод с использованием map()
и join()
:
const genreArr = [
{id: 12, name: "Adventure"},
{id: 28, name: "Action"},
{id: 878, name: "Science Fiction"}
];
const genre = document.getElementById('genre');
/* Create an array containing only the 'name' values */
var genreNames = genreArr.map(function(item) {
return item['name'];
});
/* Assign the names to the div in one go, with a seperator */
genre.textContent = genreNames.join(' | ');
<div id="genre"></div>