Home > Back-end >  Having trouble reading data from an object
Having trouble reading data from an object

Time:10-21

I don't understand how to read the genre data.

"data":
  "genres": [
    {
      "id": 0,
      "type": "string",
      "name": "string",
      "url": "string"
    },
    {
      "id": 1,
      "type": "string",
      "name": "string",
      "url": "string"
    }
  ],
}

I want it to end up being displayed like name1, name2, name3 and (if possible) I want to have each of the names have the link to their corresponding url.

I have tried to find that data by

var genres = data.genres;

But that just returns [object Object],[object Object] Im guessing that you have to read the data from those objects, but I don't know how to.

CodePudding user response:

What you need to understand from that is the following: "data" is an object and it has a "genres" property which has an array of objects inside it. Knowing this you can just do the following:

const name1 = data.genres[0].name; // Gets the first name
const name2 = data.genres[1].name; // Gets the second name

If you want to loop through the genre data, then you need to iterate through the objects inside the "genres" property:

data.genres.map((genre) => console.log(genre.name)); // Logs all names

This would be a more common example:

for (let i = 0; i < data.genres.length; i  ) {
    const name = data.genres[i].name;
    console.log(name); // Logging the names
}

CodePudding user response:

You'll have to loop to go through the data, and create a-elements to create a link. You'll also need a parent element to append the links to:

const yourParentElement = document.getElementById("parent");
var genres = data.genres;
genres.forEach(genre => { 
    var lnkGenre = document.createElement("a"); 
    lnkGenre.textContent = genre.name;
    lnkGenre.href = genre.url;
    

You can also add classes or an id here:

    lnkGenre.classList.add("yourClass");
    lnkGenre.id = genre.id;
    yourParentElement.appendChild(lnkGenre);
});
  • Related