javascript - 使用 JavaScript 从 JSON 动态表

标签 javascript jquery json

我使用以下json来开发表结构。但我无法继续根据列添加行。

[
{
"authType": "BasicAuth",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "username": "developer"
    },{
      "password": "password123"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "username": "tester"
    },{
      "password": "password123"
    }]
  }
]
},
{
"authType": "AccessToken",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "token": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/developer"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "token": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/testing"
    }]
  }
]
},
{
"authType": "OAuth",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/development"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/testing"
    }]
  }
]
}
]

我使用以下脚本来迭代 json。

var subTable = '<div class="subtable"><table data-clicked-parent-row="'+ clickedCell.row
            +'" data-clicked-column="'+ clickedCell.column +'"><tr><th>Keys</th>';
    tableData.forEach(function(e){
        if(rowType == e.authType){
            var phases;
            e.phases.forEach(function(t){
                subTable += '<th>'+ t.type +'</th>'
            })
            return subTable + '</tr></table></div>';
        }
    })

问题是,我无法在迭代对象时向表中添加行。以下是该表的静态版本。我如何编写一个通用函数来实现以下表结构。请让我知道编写迭代的更好方法。

enter image description here

最佳答案

var data = {
    "Items": [
        { 
            "id": "A004"
            , "name": "ACC LR2"
            , "userId": ["1","2","3","4"]
        }, { 
            "id": "0001"
            , "name": "ABG IT"
            , "userId": ["8","9","10","11"]
        }
    ]
}

function getUserId(obj){
    result = []
    obj.Items.forEach( function(item, i){
        result.push(item.userId);
    });
    return result;
}

function getUserIdAll(obj){
    result = []
    obj.Items.forEach( function(item, i){
        result = result.concat(item.userId);
    });
    return result;
}

console.log( getUserId(data) );
console.log( getUserIdAll(data) );

var data = [
  {
    "authType": "BasicAuth",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "username": "developer"
          },
          {
            "password": "password123"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "username": "tester"
          },
          {
            "password": "password123"
          }
        ]
      }
    ]
  },
  {
    "authType": "AccessToken",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "token": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/developer"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "token": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/testing"
          }
        ]
      }
    ]
  },
  {
    "authType": "OAuth",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/development"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/testing"
          }
        ]
      }
    ]
  }
];

function objGetKeyVal(obj){
    for (var key in obj) {
        return [ key, obj[key] ];
    }
}

(function createTable(tableData){
    var table = '<table>';
    // tableHeader += '<caption>Caption</caption>';
    // Creating table header

    // table += '<tr>';
    // table += '<th>Keys</th>';
    // table += '<th>Development</th>';
    // table += '<th>Testing</th>';
    // table += '</tr>';

    // Sub tables iterator
    tableData.forEach(function(subTable, i){
        tableRows = [];     // Rows array for sub table

        table += '<tr><th>Keys</th>';   // Table headers creating

        subTable.phases.forEach(function(colData, icol){
            
            table += '<th>'+colData.type+'</th>';   // Creating table headers for each phases

            colData.keys.forEach(function(key, irow){  // Converts structured data to array of rows arrays of columns
                if( tableRows[irow] === undefined) { tableRows[irow] = []; }
                rowData = objGetKeyVal(key);
                tableRows[irow][0] = rowData[0];
                tableRows[irow][icol+1] = rowData[1];
            });

        });
        
        table += '</tr>';               // End table header cration

        // Now we have usual table array - need only convert it to HTML
        // table looks like: [ ['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'] ]
        table += '<tr><th colspan="3">'+subTable.authType+'</th></tr>';
        tableRows.forEach(function(row){
            table += '<tr>';
            row.forEach(function(str){ 
                table += '<td>'+str+'</td>';
            });
            table += '</tr>';
        });
        
    });

    table += '</table>';
    $('body').append(table);
    
})(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 使用 JavaScript 从 JSON 动态表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33669985/

相关文章:

python - 如何从 python 中的多个列表创建 JSON 格式的字符串?

jquery - X 可编辑选择从 MVC Controller 加载的值

javascript - knockout 验证 - 验证未绑定(bind)到正确的对象实例

Javascript - 在控制台中设计文本

javascript - 箭头函数是否具有像 Groovy Closure 一样的委托(delegate)属性

javascript - 如何在jQuery中获取输入类型复选框和单选框的类型

javascript - 如何查找当前TD是否是TR中的最后一个TD

JqueryUI Datepicker 年份选择器不更新文本框文本

javascript - 如何在JavaScript代码中直接使用struts2组件?

php - 将单个表中的数据获取到多个 json 数组中