草庐IT

javascript - 将嵌套的 JSON 数据转换为 HTML 表格?

coder 2025-03-13 原文

我正在尝试使用 javascript 将此 JSON 数据转换为 HTML 表格。

到目前为止,这是我的代码;但是,我对如何处理 'contacts' 感到困惑部分并将它们放入这样的单元格中:first_name + last_name + position of the CEO and CTO .

我正在考虑使用 company_info[i]["contacts"].forEach(function(e){}提取联系人数据,但我不确定如何将其放在单元格中。

感谢任何帮助!

我的代码:

function CreateTableFromJSON() {
  var company_info = [{
      "id": 1,
      "company_name": "ACompany",
      "established": 1999,
      "industry": "Tech",
      "contacts": [{
          "first_name": "AAFirst",
          "last_name": "AALast",
          "position": "CEO"
        },
        {
          "first_name": "ABFirst",
          "last_name": "ABLast",
          "position": "CTO"
        }
      ]
    },
    {
      "id": 2,
      "company_name": "BCompany",
      "established": 1998,
      "industry": "Med",
      "contacts": [{
          "first_name": "BAFirst",
          "last_name": "BALast",
          "position": "CEO"
        },
        {
          "first_name": "BBFirst",
          "last_name": "BBLast",
          "position": "CTO"
        }
      ]
    },
    {
      "id": 3,
      "company_name": "CCompany",
      "established": 1997,
      "industry": "Ivest",
      "contacts": [{
          "first_name": "CAFirst",
          "last_name": "CALast",
          "position": "CEO"
        },
        {
          "first_name": "CBFirst",
          "last_name": "CBLast",
          "position": "CTO"
        }
      ]
    },
    {
      "id": 4,
      "company_name": "DCompany",
      "established": 1996,
      "industry": "Tech",
      "contacts": [{
          "first_name": "DAFirst",
          "last_name": "DALast",
          "position": "CEO"
        },
        {
          "first_name": "DBFirst",
          "last_name": "DBLast",
          "position": "CTO"
        }
      ]
    },
    {
      "id": 5,
      "company_name": "ECompany",
      "established": 1995,
      "industry": "Med",
      "contacts": [{
          "first_name": "EAFirst",
          "last_name": "EALast",
          "position": "CEO"
        },
        {
          "first_name": "EBFirst",
          "last_name": "EBLast",
          "position": "CTO"
        }
      ]
    }
  ]
  // EXTRACT VALUE FOR HTML HEADER. 
  // ('ID', 'Company Name', 'Established','Industry', 'Contacts')

  var col = [];

  for (var i = 0; i < company_info.length; i++) {
    for (var key in company_info[i]) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }
  }
  //Create a table
  var table = document.createElement("table");
  //Create  table rows
  var tr = table.insertRow(-1);
  //Create table headers
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th"); // TABLE HEADER.
    th.innerHTML = col[i];
    tr.appendChild(th);
  }

  //Add JSON data to table as rows
  for (var i = 0; i < company_info.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      var tabCell = tr.insertCell(-1);
      tabCell.innerHTML = company_info[i][col[j]];

    }
  

}

var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        table, th, td 
        {
            margin:10px 0;
            border:solid 1px #333;
            padding:2px 4px;
            font:15px Verdana;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
    <div id="showData"></div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

  

最佳答案

据我了解,您想将联系人数组放在单元格中。我们知道 contacts 列在嵌套的 for 循环中是 4。您可以编写一个简单的 if 验证来检查当前 j 是什么。如果 j 不是 4,即 contacts 列,则在表中插入值。如果当前 j 值为 4,则再进行一个嵌套 for 循环,它将在每个对象中循环 contacts 数组。

  var company_info = [{
      "id": 1,
      "company_name": "ACompany",
      "established": 1999,
      "industry": "Tech",
      "contacts": [{
        "first_name": "AAFirst",
        "last_name": "AALast",
        "position": "CEO"
      }, {
        "first_name": "ABFirst",
        "last_name": "ABLast",
        "position": "CTO"
      }]
    }, {
      "id": 2,
      "company_name": "BCompany",
      "established": 1998,
      "industry": "Med",
      "contacts": [{
        "first_name": "BAFirst",
        "last_name": "BALast",
        "position": "CEO"
      }, {
        "first_name": "BBFirst",
        "last_name": "BBLast",
        "position": "CTO"
      }]
    }, {
      "id": 3,
      "company_name": "CCompany",
      "established": 1997,
      "industry": "Ivest",
      "contacts": [{
        "first_name": "CAFirst",
        "last_name": "CALast",
        "position": "CEO"
      }, {
        "first_name": "CBFirst",
        "last_name": "CBLast",
        "position": "CTO"
      }]
    }, {
      "id": 4,
      "company_name": "DCompany",
      "established": 1996,
      "industry": "Tech",
      "contacts": [{
        "first_name": "DAFirst",
        "last_name": "DALast",
        "position": "CEO"
      }, {
        "first_name": "DBFirst",
        "last_name": "DBLast",
        "position": "CTO"
      }]
    }, {
      "id": 5,
      "company_name": "ECompany",
      "established": 1995,
      "industry": "Med",
      "contacts": [{
        "first_name": "EAFirst",
        "last_name": "EALast",
        "position": "CEO"
      }, {
        "first_name": "EBFirst",
        "last_name": "EBLast",
        "position": "CTO"
      }]
    }]
    // EXTRACT VALUE FOR HTML HEADER. 
    // ('ID', 'Company Name', 'Established','Industry', 'Contacts')

  var col = [];

  for (var i = 0; i < company_info.length; i++) {
    for (var key in company_info[i]) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }
  }
  //Create a table
  var table = document.createElement("table");
  //Create  table rows
  var tr = table.insertRow(-1);
  //Create table headers
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th"); // TABLE HEADER.
    th.innerHTML = col[i];
    tr.appendChild(th);
  }

  //Add JSON data to table as rows
  for (var i = 0; i < company_info.length; i++) {

    tr = table.insertRow(-1);

    for (var j = 0; j < col.length; j++) {
      var tabCell = tr.insertCell(-1);
      if (j !== 4) {
        tabCell.appendChild(document.createTextNode(company_info[i][col[j]]));
      } else {
        for (var x = 0; x < company_info[i].contacts.length; x++) {
          var firstName = company_info[i].contacts[x].first_name,
            lastName = company_info[i].contacts[x].last_name,
            position = company_info[i].contacts[x].position;

          tabCell.appendChild(document.createTextNode(" " + firstName + " " + lastName + ", " + position));
        }
      }
    }

  }


  var divContainer = document.getElementById("showData");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
<div id="showData">

</div>

让我知道这是否是您想要的。如果没有,我将编辑答案。

关于javascript - 将嵌套的 JSON 数据转换为 HTML 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915321/

有关javascript - 将嵌套的 JSON 数据转换为 HTML 表格?的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  7. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  8. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  9. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  10. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

随机推荐