将JSON数据转换为表 [英] Convert JSON data to table

查看:137
本文介绍了将JSON数据转换为表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据如下所示的JSON数据创建表:

I am trying to create table from my JSON data which looks like this:

它适用于特定的JSON数据:

It works for a specific JSON data:

var items = [
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]

但是,如果列(类型")是随机的,则无法正确创建表

But, it doesn't create table correctly if the columns ("Type") is random

var items = [
{"Name":"A","Type":5,"Result":"1"}
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":3,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]

有人可以告诉我我的代码有什么问题吗? 我想为动态JSON数据创建表,该表可能没有所有列的单元格值.使用此代码,我看不到A的第5列中的条目为1.

Can someone tell me what's the issue with my code? I want to create table for dynamic JSON data which may not have cell values for all the columns. With this code, I don't see entry in column 5 for A as 1.

function get_prop(obj, prop) {
   return prop.split('.').reduce((o,k) => obj[k], obj);
}

function coll2tbl(json, row_header, col_header, cell) {
var table = {};
var row_headers = [];
var cols = {};

json.map(function(a) {
    var h = get_prop(a, row_header);
    if (h in table === false) {
        table[h] = {};
        row_headers.push(h);
    }
    var c = get_prop(a, col_header);
    cols[c] = null;
    table[h][c] = get_prop(a, cell);
});

var cells = [];
for (var row in table) {
    cells.push(Object.values(table[row]));
}
console.log('row_headers' + row_headers);
console.log('Object.keys(cols)' + Object.keys(cols));
console.log('cells' + cells);

var headerRow = '<th>' + capitalizeFirstLetter('TestName') + '</th>';
var colKeys = Object.keys(cols);
colKeys.map(function(col) {
 headerRow += '<th>' + capitalizeFirstLetter(col) + '</th>';
});

var bodyRows = '';
for (var i in cells) {
  bodyRows += '<tr>'; 
  bodyRows += '<td>' + row_headers[i] + '</td>';
  for (var j in cells[i]) {
    console.log('Processing row: ' + row_headers[i] + ' result: ' + cells[i][j] + ' i=' + i + ' j=' + j);
    bodyRows += '<td>';
    if (cells[i][j] === "1") {
      bodyRows +=  '<font color="green">' + cells[i][j] + '</font>';
    }
    else if (cells[i][j] === "0") {
      bodyRows +=  '<font color="red">' + cells[i][j] + '</font>';
    }
    else if (cells[i][j] === "-1") {
      bodyRows +=  '<font color="orange">' + cells[i][j] + '</font>';
    }
    else {
      bodyRows +=  "-";
    }
    bodyRows += '</td>';
  }
  bodyRows += '</tr>';
}

//return { row_headers, col_headers: Object.keys(cols), cells };
return ('<table> <thead><tr>' + headerRow + '</tr></thead><tbody>' + bodyRows + '</tbody></table>');
}

function capitalizeFirstLetter(string) {return 
    string.charAt(0).toUpperCase() + string.slice(1);
}

coll2tbl(items, 'Name', 'Type', 'Result');

我的桌子应该像这样:

Name 1 2 3 4 5 
A    1 1 - - 1 
B    1 1 1 - -

推荐答案

答案 https://stackoverflow.com/a/52199138 /10320683 当然是正确的,但是如果您需要或想要坚持自己的特定代码,可以将其放在json.map下面(应该使用

The answer https://stackoverflow.com/a/52199138/10320683 is of course correct, but if you need or want to stick to your specific code, you can put this below your json.map (which should by the way use forEach and not map, since you do not use the returned array anyways)

  for (var col in cols) {
    for (row in table) {
      if (!table[row].hasOwnProperty(col)) {
        table[row][col] = "-";
      }
    }
  }

您的代码无法正常工作的原因是,通过遍历行,您无法获得所有可能的类型属性,如果您检查table变量,则会变得很清楚:{ a: {1: "1", 2: "0", 5: "1"}, b: {...}}(这遗漏了3类型属性),因此稍后通过调用Object.values(table[row]),您将为您的单元格获得以下数组:["1", "0", "1"],但是您确实有4列,因此类型5"结果(1)向左移了一列

The reason why your code did not work is that by iterating over the rows, you do not get all the possible type properties, which becomes clear if you inspect your table variable: { a: {1: "1", 2: "0", 5: "1"}, b: {...}} (this is missing the 3 type property), so by calling Object.values(table[row]) later on, you get the following array for your cells: ["1", "0", "1"], but you do have 4 columns, so the "Type 5" result (1) gets shifted one column to the left.

此外,您还需要小心,因为您的代码依赖于Object.values()产生的排序,这意味着,如果您想更改列的顺序,则代码将无法工作.

Also, you need to be careful because your code is relying on the sorting that Object.values() produces, which means that if you want to change the order of your columns, your code would not work.

这篇关于将JSON数据转换为表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆