0

I am new to JS and I have a problem and can't get the solution. I have written a backend with Java SE, Jersey and Jackson. Everything is fine. My REST endpoint is running. But I cannot figure how to reference that json array object. The "time" values are working correct. The array of "team" say always "undefined".

I want to fill a HTML table with those values. Here is the code snippet:

<script>
    var dataExchange = []

    $.ajax({
        method:'GET',
        url:'http://localhost:8080/api/calendar',
        success:function(response){
            dataExchange = response
            buildTable(dataExchange)
            console.log(dataExchange)
        }
    })

    function buildTable(data){
        var table = document.getElementById('eventTable')

        for (var i = 0; i < data.length; i++){

             var row = `<tr>
                            <td>${data[i].dateOfEvent}</td>
                            <td>${data[i].team.teamName}</td> <---Here is the problem
                      </tr>`
             table.innerHTML += row
        }
    }
</script>

Thats the JSON from the backend:

[{"dateOfEvent":"2019-07-18T18:30","team":[{"teamName":"Salzburg"}]},{"dateOfEvent":"2019-07-18T18:30","team":[{"teamName":"Sturm"}]},{"dateOfEvent":"2019-10-23T09:45","team":[{"teamName":"Capitols"}]},{"dateOfEvent":"2019-10-23T09:45","team":[{"teamName":"KAC"}]}]

Please, can anyone explain what I am doing wrong here and how does this exactly work with JavaScript?

2
  • 1
    Are you parsing data before using it in the function? Commented Jan 23, 2021 at 18:58
  • What does the console.log(dataExchange) output in the console? A string or an object? Commented Jan 23, 2021 at 19:00

2 Answers 2

1

data[i].team is not an object - it is an array with one object. You need to use data[i].team[0].teamName:

function buildTable(data) {
  var table = document.getElementById('eventTable');

  for (var i = 0; i < data.length; i++) {
    var row = `<tr>
                 <td>${data[i].dateOfEvent}</td>
                 <td>${data[i].team[0].teamName}</td>
               </tr>`
    table.innerHTML += row;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Based on your json it has to be something like this:

<td>${data[i].team[0].teamName}</td>

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.