etru_RU

Harjutus 2: JSON andmete näitamine JS kaudu

  1. Ava veebilehitsejas Code Sandbox sait
  2. Vali kollase taustaga JavaScript

3. Loo fail index.js

import "./styles.css";

const car = [
  {
    Name: "HONDA",
    Color: "red",
    "Tinted windows": false,
    Wheel: 3,
    "Roof cargo": null,
    Entertaiment: [
      "FM radio",
      "MP3, MP4 and MKV player",
      "harman/karbon speakers",
    ],
    Accessories: ["satnav", "cruise control"],
  },
  {
    Name: "SAAB",
    Color: "blue",
    "Tinted windows": false,
    Wheel: 4,
    "Roof cargo": null,
    Entertaiment: [
      "FM radio",
      "MP3, MP4 and MKV player",
      "harman/karbon speakers",
    ],
    Accessories: ["satnav", "cruise control"],
  },
  {
    Name: "TOYOTA",
    Color: "white",
    "Tinted windows": true,
    Wheel: 4,
    "Roof cargo": "Bike rack",
    Entertaiment: ["Satellite radio", "Bluetooth", "Touchscreen display"],
    Accessories: ["rear camera", "heated seats"],
  },
];

//näita html tabelina
document.getElementById("app").innerHTML = `
  <div>
    <h1>Car properties</h1>
    <table border="1" cellpadding="5">
      <thead>
        <tr>
          <th>Name</th>
          <th>Color</th>
          <th>Tinted Windows</th>
          <th>Wheels</th>
          <th>Roof Cargo</th>
          <th>Entertainment</th>
          <th>Accessories</th>
        </tr>
      </thead>
      <tbody>
        ${car
          .map(
            (car) => `
          <tr>
            <td>${car.Name}</td>
            <td>${car.Color}</td>
            <td>${car["Tinted windows"] ? "Yes" : "No"}</td>
            <td>${car.Wheel || "N/A"}</td>
            <td>${car["Roof cargo"] || "None"}</td>
            <td>${car.Entertaiment.map((e) => "🪭" + e).join(", ")}</td>
            <td>${car.Accessories.join(", ")}</td>
          </tr>
        `
          )
          .join("")}
      </tbody>
    </table>
  </div>
`;

Salvestame, uuendame lehekülge ja näeme tulemust.

Kokkuvõte

Auto andmet on JSON masiivis mida pärast me kuvame html tabelina JS abil.