I am doing a project which uses The Movie Db API and I am bit confused with displaying following object:
(3) [{…}, {…}, {…}]
0: {id: 12, name: "Adventure"}
1: {id: 28, name: "Action"}
2: {id: 878, name: "Science Fiction"}
length: 3
__proto__: Array(0)
Basically, I am trying to figure out how to display those 3 genres in one element. Doing forEach loop like this :
const genreArr = data.genres;
console.log(genreArr)
genreArr.forEach(function(item){
genre.textContent = item.name;
})
displays only one name of genre rather than all of them. So, what do I have to do to display all of those in one paragraph?
This line genre.textContent = item.name;
will overwrite the textContent
every iteration of forEach
leaving only the last value.
You need append to textContent
using +=
.
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>
An alternate, more efficient method using map()
and 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>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다