rtwhite
rtwhite

Reputation: 399

How to correctly iterate over and object in array thats contained with in an array

Im having issues correctly displaying the data in a json file. The data is for cells in a row and each object is a new row with the inner array correlating to the row data. But what is tricky is that instead of having the data hard coded in for the 3 cells there, planID infers how many cells that data should cover.

here is the json

"lorem": [
    {
      "name": "ipsum",
      "availability": [
        {
          "planID": [1],
          "description": "2source"
        },
        {
          "planID": [2, 3],
          "description": "Unlimited"
        }
      ]
    },
    {
      "name": "lorem",
      "availability": [
        {
          "planID": [1,2,3],
          "description": "check"
        }
      ]
    }
  ]

so the table should look like

any tips on how to do this dynamically would be amazing. Also this is for a react project. Thanks!

Upvotes: 1

Views: 56

Answers (1)

Iago Calazans
Iago Calazans

Reputation: 328

Ok! Iterating through it and generating a table should look like this:

// i create a const named json with the JSON value.
const json = {
  "lorem": [{
      "name": "ipsum",
      "availability": [{
          "planID": [1],
          "description": "2source"
        },
        {
          "planID": [2, 3],
          "description": "Unlimited"
        }
      ]
    },
    {
      "name": "lorem",
      "availability": [{
        "planID": [1, 2, 3],
        "description": "check"
      }]
    }
  ]
}

// get the table by id on the document
const table = document.getElementById('table');

// start iterating obj of json.lorem
for (let obj of json.lorem) {

  // create tr (table row) & th (table header)
  const tr = document.createElement('tr');
  const th = document.createElement('th');
  th.innerText = obj.name
  tr.appendChild(th); // insert th into tr

  // start iterating over obj.availability
  for (let availability of obj.availability) {
    for (let planID of availability.planID) {

      //create td (table data)
      const td = document.createElement('td');
      td.innerText = availability.description;
      tr.appendChild(td); // insert td into the tr created above
    }
  }

  // insert the above created on each for run on the table
  table.appendChild(tr);
}

console.log(table);
<table border="1" id="table">

</table>

Upvotes: 1

Related Questions