在表中输出一些但不是全部的 php 编码 JSON 数据

我有这个来自 php 的变量,我正在转向 JSON


var myData = <?php echo json_encode($json_array) ?>; 

当我得到控制台日志时,输出格式是这样的:


0:

Carat: "0.70"

Clarity: "VVS2"

Color: "D"

Cut: "Very Good"

Polish: "Fair"

Price: "2806"

Product ID: "17"

Product Name: "0.7 Carat Cushion Diamond"

Report: "IGI"

Shape: "Cushion"

Symmetry: "Ideal"

purl: "http://klaussongs.com/product/0-7-carat-cushion-diamond/"

__proto__: Object

1: {Product ID: "19", Product Name: "0.9 Carat Round Diamond", Carat: "0.90", Clarity: "VS2", Shape: "Round", …}

2: {Product ID: "21", Product Name: "1 Carat Radiant Diamond", Carat: "1.00", Clarity: "SI1", Shape: "Radiant", …}

问题是我正在使用 objects.key 来获取克拉、净度、切割等,但键是 0、1、2,在对象之前:如何更改以下代码以仅使用其中一些生成我的表键,例如(克拉、净度、价格等)删除一些我不想要的,例如产品 ID 并生成表格。现在,当我生成表时,标题是 0、1、2、3,这是 JSON var 父键,但我想选择(不是全部)但一些子键。感谢所有帮助。


      function generateTableHead(table, data) {

      let thead = table.createTHead();

      let row = thead.insertRow();

      for (let key of data) {

        let th = document.createElement("th");

        let text = document.createTextNode(key);

        th.appendChild(text);

        row.appendChild(th);

      }

    }


    function generateTable(table, data) {

      for (let element of data) {

        let row = table.insertRow();

        for (key in element) {

          let cell = row.insertCell();

          let text = document.createTextNode(element[key]);

          cell.appendChild(text);

        }

      }

    }



    let table = document.querySelector("#simpleTable");



    let data = Object.keys(myData);



    // create selected tbody as values

    generateTable(table, myData);



    // create selected thead as keys 

    generateTableHead(table, data);


幕布斯7119047
浏览 213回答 1
1回答

一只萌萌小番薯

使用包含要显示的属性的数组,而不是遍历所有列。const myColumns = ["Carat", "Clarity", "Color"];function generateTable(table, data, columns) {&nbsp; for (let element of data) {&nbsp; &nbsp; let row = table.insertRow();&nbsp; &nbsp; for (key in columns) {&nbsp; &nbsp; &nbsp; let cell = row.insertCell();&nbsp; &nbsp; &nbsp; let text = document.createTextNode(element[key]);&nbsp; &nbsp; &nbsp; cell.appendChild(text);&nbsp; &nbsp; }&nbsp; }}function generateTableHead(table, data) {&nbsp; let thead = table.createTHead();&nbsp; let row = thead.insertRow();&nbsp; for (let key of data) {&nbsp; &nbsp; let th = document.createElement("th");&nbsp; &nbsp; let text = document.createTextNode(key);&nbsp; &nbsp; th.appendChild(text);&nbsp; &nbsp; row.appendChild(th);&nbsp; }}generateTable(table, myData, myColumns);generateTableHead(table, myColumns);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript