【问题标题】:How to load Json array into separate table rows?如何将 Json 数组加载到单独的表行中?
【发布时间】:2020-05-28 13:18:59
【问题描述】:

我无法正确显示我的 json 数据。我想获取每种产品并将它们放入自己的行中。

现在的问题是它将所有数据(例如值“name”)放入一个表行而不是多行。

这是我的 json 数据

{
 id: "FVFkkD7s8xNdDgh3zAyd",
 name: "AlperKaffe",
 products: [
 {
   id: "0cfBnXTijpJRu14DVfbI",
   name: "Første Kaffe",
   price: "1",
   size: "small",
   quantity: "20 ml"
},
{
   id: "JQadhkpn0AJd0NRnnWUF",
   name: "Anden Kaffe",
   price: "2",
   size: "Medium",
   quantity: "25 ml"
},
{
   id: "UwHHdH8bFxbVHkDryeGC",
   name: "kaffeeen",
   price: "300",
   size: "Small",
   quantity: "23 ml"
},
{
   id: "WiX5h0wFMNkCux9cINYq",
   name: "kaffe modal",
   price: "230",
   size: "Medium",
   quantity: "39 ml"
},

这是我获取 json 数据的 Js 文件。如您所见,我现在只使用“名称”值

  // Jquery getting our json order data from API
  $.get("http://localhost:8888/products", (data) => {    

    let rows = data.map(item => {

      let $clone = $('#frontpage_new_ordertable tfoot tr').clone();

      let productsName = item.products.map(prod => `${prod.name}`);
      $clone.find('.name').html(productsName);

      return $clone;
    });

    // appends to our frontpage html 
    $("#frontpage_new_ordertable tbody").append(rows);


    });

这是我的 html 文件

<body>  
   <table id="frontpage_new_ordertable">
    <tbody>
      <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Size</th>
        <th>Quantity</th>
        <th></th>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td class="name"></td>
        <td class="price"></td>
        <td class="size"></td>
        <td class="quantity"></td>
        <td class="buttons"></td>
      </tr>
    </tfoot>
  </table>

  <script src="./itemPage.js"></script>

</body>

【问题讨论】:

    标签: javascript html arrays json


    【解决方案1】:

    你必须更换 let rows = data.map(item =&gt; {let rows = data.products.map(item =&gt; {

          let productsName = item.products.map(prod => `${prod.name}`);
    

          let productsName = item.name;
    

    https://jsfiddle.net/ab7t1vmf/3/

    【讨论】:

      【解决方案2】:

      您的 JS sn-p 中的问题似乎是 let rows = data.map(item =&gt; { ...

      根据您的描述,JSON 数据由 3 个键组成:

      • 身份证
      • 姓名
      • 产品

      您不能直接在 Javascript 对象上执行 map 函数,该函数需要一个数组。

      仔细查看您的代码,我知道您需要在自己的行中显示每个产品。因此,您需要在包含(产品)数组的 data.products 上使用 map 函数。

      let rows = data.products.map(item => {
          // ...
          $clone.find('.name').html(item.name);
          // ...
      // ...
      });
      

      参考:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 2020-11-04
        • 1970-01-01
        相关资源
        最近更新 更多