1

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?

1
  • you're overriding the last genre with the next one, consider using +=, or better, accumulate a string and then set it once your done to avoid updating the dom multiple times Commented Jun 17, 2020 at 14:58

3 Answers 3

2

You could do something like this

let arr = [];
let sentence = '';

genreArr.forEach(el => {
  arr.push(el.name);
  sentence += ' ' + el.name;
})

console.log(arr)
console.log(sentence)
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

You can use map and do your operation easily

const arraryList = [{id: 12, name: "Adventure"},
{id: 28, name: "Action"},
{id: 878, name: "Science Fiction"}];

const output = arraryList.map(val => val.name);
const combinedName = output.join(",");
console.log(output);
console.log(combinedName);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.