【问题标题】:Array of Json(dynamic keys) + table format +angular5Json数组(动态键)+表格格式+angular5
【发布时间】:2018-11-03 14:20:00
【问题描述】:

我从我的 API 收到 JSON 作为响应,我必须将该数据显示到表结构中。

考虑 JSON 如下:

[
{
"key1":"value1",
"key2" :"value2"
},
{
"key1":"value3",
"key2" :"value4"
}
]

但是key1key2 不是固定的,每次都会改变,所以我必须将API 接收到的内容显示为表结构。我提到了很多关于动态键的内容。 我提到了这个https://medium.com/codingthesmartway-com-blog/angular-material-part-4-data-table-23874582f23a

但必须显示动态内容。

编辑

我想要以下结构:

key1    key2
value1  value2
value3  value4

Create Table from JSON Data with angularjs and ng-repeat answerBy SantoshK 我想我需要,但它对我来说显示空白表。

【问题讨论】:

  • 你能添加一些你的代码吗?
  • 所以您想用索引遍历您的 json 键/值,对吗?喜欢json[0].key = "key1"json[0].value = "value1"
  • @Sravan 在您的代码中假设 name: string; position: number; weight: number; symbol: string; 不是固定的,如果您不知道密钥,是我的情况
  • 在 html 中没有任何键.. 它是动态的

标签: node.js angular angular5


【解决方案1】:

你可以试试这个(仅供参考):

<!DOCTYPE html>
<html>
   <title>Web Page Design</title>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
   </head>
   <table>
      <thead>
         <tr>
            <th>Value</th>
         </tr>
      </thead>
      <tbody id="tableId">

      </tbody>
   </table>
   <script>
      function sayHello() {
         var sample = [{"key1":"value1","key2" :"value2"},{"key1":"value1","key2":"value2"}]


         for (key in sample){
             for (currVal in sample[key]){
                $('#tableId').append('<tr><td>'+sample[key][currVal]+'</td></tr>')
             }
         }

      }
      sayHello();
   </script>
   <body></body>
</html>

【讨论】:

  • 这里是否必须使用jquery??
【解决方案2】:

这里有一个解决办法,你应该用Object.keys来获取objectdynamic键值

组件:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  candidature = "test";
  data =[
{
"key1":"value1",
"key2" :"value2"
},
{
"key1":"value3",
"key2" :"value4"
}
]

getKeys(schedule_data){
  return Object.keys(schedule_data);

}
 }

HTML:

<table>  
<th *ngFor="let sch of getKeys(data[0])">
  {{sch}}
      <div *ngFor="let schedule_data of data">
        {{schedule_data[sch]}}
    </div>
</th>
</table>

Here is a working DEMO

【讨论】:

  • 我找到了一个链接stackoverflow.com/questions/43864288/…,它达到了我的预期
  • 请查看我的演示,它还创建了动态键
  • @Subburaj,可以吗?
  • @Subburaj,我更改了我的答案以使其符合您需要的格式。请检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2021-12-20
  • 2020-02-22
  • 2020-11-20
  • 1970-01-01
相关资源
最近更新 更多