0

I'm trying to get data from .JSON file and import in inner HTML but it keeps giving me an error where it says " data.forEach(function(user) is not a function "

my codes below:

<!DOCTYPE html>
<html>
<head>
    <title>personen</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

</head>
<body>
    <button id="button_get_all_persons">get all persons</button><br/><br/>
    <button id="button_get_person">get person</button>id: <input type="text" id="txt_id"/><br/><br/>
    <button id="button_post_person">post</button> name: <input type="text" id="txt_name"/><br/><br/>

    <hr>

    <div id="output"></div>

    <script>

        document.getElementById('button_get_all_persons').addEventListener
        ('click',getUsers);

function getUsers(){
              fetch('persons.json')
              .then((res) => res.json())
              .then((data) =>{
                  let output = '<h2>Users</h2>';
                  data.forEach(function(user){
                      output += `
                        <ul class="list-group mb-3">
                        <li class="list-group-item">ID: ${user.id}</li>
                        <li class="list-group-item">Name: ${user.name}</li>
                        </ul>
                      `;
                  });
                  document.getElementById('output').innerHTML = output;
              }) 
          }
   </script>
</body>
</html>

here is my .JSON file

{
  "persons": [
    {
      "id": 1,
      "name": "jan"
    },
    {
      "id": 2,
      "name": "tim"
    },
    {
      "id": 3,
      "name": "ali"
    },
    {
      "name": "dirk",
      "id": 4
    }
  ]
}

can someone explain to me the situations pls, I'm new to JS . Thank you in advance !

3
  • data is not an array, is an object, so .forEach won't work, since forEach is from Array.prototype Commented Mar 20, 2020 at 14:24
  • 2
    data.persons.forEach() Commented Mar 20, 2020 at 14:25
  • thx, any advice where I can practise js ? Commented Mar 20, 2020 at 14:28

1 Answer 1

3

forEach is a method found on arrays.

data is not an array, it is a plain object.

data.persons is an array and does have a forEach method.

Sign up to request clarification or add additional context in comments.

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.