Lesson 4 โ€” Your Herd as Data

JSON ยท the table is built from a list, not typed by hand

Four animals in HTML is fine. Forty is a mess. On a real place you do not rewrite the whole webpage when a calf is born. You update a list. JSON is how we write that list: names, tags, weights โ€” something the computer can loop over.

Here is the finished look

Same card. The rows are drawn by JavaScript from a list, not typed as table cells.

Step 1 โ€” what one animal looks like as data

Curly braces. A name on the left, a value on the right. Quotes around text. Numbers bare. Commas between the pairs.

{
  "name": "Black Gold",
  "tag": "FW-01",
  "breed": "Texas Longhorn",
  "notes": "Rare black pattern, 100\"+ horns",
  "startWeight": 1100,
  "currentWeight": 1280
}

The whole herd is those objects inside square brackets, separated by commas. Think of it as a record book the computer can read.

Step 2 โ€” keep the list in script.js for now

Next lesson the list moves into its own file. Today it still lives in JavaScript, and the empty table body gets filled from that list.

var herd = [
  { "name": "Black Gold", "tag": "FW-01", "startWeight": 1100, "currentWeight": 1280 },
  { "name": "Brutus", "tag": "FW-02", "startWeight": 1400, "currentWeight": 1520 },
  { "name": "McCree", "tag": "FW-03", "startWeight": 1200, "currentWeight": 1310 },
  { "name": "Blacksmith", "tag": "FW-04", "startWeight": 1050, "currentWeight": 1180 }
];

var tbody = document.getElementById("herd-body");
herd.forEach(function (animal) {
  var gain = animal.currentWeight - animal.startWeight;
  tbody.insertAdjacentHTML("beforeend",
    "<tr><td>" + animal.name + "</td><td>" + animal.tag + "</td><td>" +
    animal.startWeight + "</td><td>" + animal.currentWeight + "</td><td>" +
    gain + " lbs</td></tr>"
  );
});

Add a fifth animal to the list, save, refresh. The table should grow. That is the whole point of this lesson. The page is no longer the record book. The list is.

โ† Lesson 3 All lessons Lesson 5 โ†’