My html not displaying the local json file after fetching it using javascript

Viewed 29

How can i edit the following cord to display the total number of impression and conversion. when i console.log(data) i get array(100000) your assistance will be highly appreciated.

<script>
    
//pulling data from local json file
fetch('./logs.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    // console.log(data);
    let data1 = "";

    data.forEach((values) => {
      data1 += ` 
            <div class="card">
            <p class="impression">${values.impression}</p>
            <p class="conversion">${values.conversion}</p>
            </div> `;
    });

    document.querySelector("#card").innerHTML = data1;

  })
  .catch((error) => {
    console.log(error);
  })
    
</script>
1 Answers

Add total variables to the code, and increment them in the forEach loop.

fetch('./logs.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    // console.log(data);
    let data1 = "";
    let totalImpressions = 0;
    let totalConversions = 0;
    data.forEach((values) => {
      totalImpressions += values.impression;
      totalConversions += values.conversion;
      data1 += ` 
            <div class="card">
            <p class="impression">${values.impression}</p>
            <p class="conversion">${values.conversion}</p>
            </div> `;
    });
    data1 += `<div>Total impressions = ${totalImpressions} Total conversions = ${totalConversions}</div>`;
    document.querySelector("#card").innerHTML = data1;

  })
  .catch((error) => {
    console.log(error);
  })

Related