Json with nested arrays

Having a issue with a json file. Can't seem to get JavaScript to render images. If I hard code it it works fine but otherwise no luck.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="cont"></div>
    <script>
      'use strict';

      const cont = document.querySelector('.cont');

      const renderDetail = function (data) {
        const html = `
    <div class="id">${data.id}</div>
    <div class="title">${data.title}</div>
    <div class="disciplines">${data.disciplines}</div>
    <div class="content">${data.content}</div>
    <div class="project_images">
      <img class="img01"src="${data.projectimages[0]}" />
      <img class="img02"src="${data.projectimages[1]}" />
      <img class="img03"src="${data.projectimages[2]}" />
      <img class="img04"src="${data.projectimages[3]}" />
      <img class="img05"src="${data.projectimages[4]}" />
      <img class="img06"src="${data.projectimages[5]}" />
      <img class="img07"src="${data.projectimages[6]}" />
    </div>
  `;
        cont.insertAdjacentHTML('beforeend', html);
      };

      const getDetailData = function (project) {
        fetch('json.json')
          .then(response => response.json())
          .then(data => renderDetail(data[0]));
      };

      getDetailData();
    </script>
  </body>
</html>

json.json (1.4 KB)
example

The issue is with these lines of code:

<img class="img01"src="${data.projectimages[0]}" />
      <img class="img02"src="${data.projectimages[1]}" />
      <img class="img03"src="${data.projectimages[2]}" />
      <img class="img04"src="${data.projectimages[3]}" />
      <img class="img05"src="${data.projectimages[4]}" />
      <img class="img06"src="${data.projectimages[5]}" />
      <img class="img07"src="${data.projectimages[6]}" />

For some reason ${data.projectimages[0]} doesn't seem to be rendered and I get this error

TypeError: Cannot read properties of undefined (reading '0')

The projectimages object only has an array in it and so why I can't access it is strange.

Any help would be much appreciated.

Cheers

Zigs

HI @ziggelflex,

the array in your json file is named project_images and not projectimages.

I even asked the duck! Feel like punching myself in the head!

Thanks @bendingrodriguez sorry mate that was a school boy error!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.