Search code examples
javascriptjsonxmlhttprequest

How can I read a node in txt file using Javascritp


I need create a list like

  • ANIMAL 1
  • ANIMAL 2
  • ANIMAL 3

And the response is in a .TXT file with some nodes

{
    "pets":[
        { "animal":"animal 1", "name":"Fido" },
        { "animal":"animal 2", "name":"Felix" },
        { "animal":"animal 3", "name":"Lightning" }
    ]
}

How can I create a JS to return the name of the animal in a DIV?


Solution

  • There's probably a better approach for this than what I did, but it's something.

    Your can iterate through your object with a for loop like this:

    const response = {
      "pets": [{
          "animal": "animal 1",
          "name": "Fido"
        },
        {
          "animal": "animal 2",
          "name": "Felix"
        },
        {
          "animal": "animal 3",
          "name": "Lightning"
        }
      ]
    };
    
    // Loop through the pets property of the response object
    for (let i = 0; i < response.pets.length; i++) {
      // Add the name property of the pets property to the div
      document.getElementById('animals').innerHTML += `${response.pets[i].name} <br>`;
    }
    <div id="animals"></div>