[英]How to use json2html with random keys
因此,如果我知道我將在json中獲取哪種類型的數據,我將清楚地理解如何將JSON轉換為HTML。
但是,如果我不知道從服務器獲得哪種密鑰,該如何使用json2html?
這里的代碼,可以正確地使用靜態鍵:
var data = {'json': [{ 'order': 'By', 'name': 'Stack', 'randomkey': '3', 'randomkey_n': '0', 'score': '121', 'id': '540' }]}; var transform = { tag: 'tr', children: [{ "tag": "td", "html": "${order}" }, { "tag": "td", "html": "${name}" }, { "tag": "td", "html": "${randomkey}" }, { "tag": "td", "html": "${randomkey_n}" }, { "tag": "td", "html": "${score}" }] }; $('#placar > tbody ').json2html(data.json, transform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://json2html.com/js/json2html.js"></script> <script src="http://json2html.com/js/jquery.json2html.js"></script> <div class="container"> <p> <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> </tr> </thead> <tbody></tbody> </table> </div>
我知道,我應該在transform
使用內聯函數,但是我不明白如何返回“隨機”鍵的值。
您可以使用Object.keys
列出屬性,使用.filter()
排除id
屬性(似乎沒有渲染它),最后將.map()
排除到children
屬性所需的對象結構中:
var data = {'json': [{ 'order': 'By', 'name': 'Stack', 'randomkey': '3', 'randomkey_n': '0', 'score': '121', 'id': '540' }]}; var transform = { tag: 'tr', children: Object.keys(data.json[0]) // get keys .filter(key => key !== 'id') // exclude id .map(key => ({ // convert to object for transformation "tag": "td", "html": "${" + key + "}" })) }; $('#placar > tbody ').json2html(data.json, transform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://json2html.com/js/json2html.js"></script> <script src="http://json2html.com/js/jquery.json2html.js"></script> <div class="container"> <p> <table id="placar" class="table table-condensed table-bordered"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> </tr> </thead> <tbody></tbody> </table> </div>
如果您還有其他應排除的屬性(例如id) ,則可以執行以下操作:
.filter(key => !['id', 'otherfield', 'comment'].includes(key))
或者,如果您有許多這樣的屬性,請先定義一次集合來提高效率:
const excludes = new Set(['id', 'otherfield', 'comment', /* many others...*/]);
...然后過濾變為:
.filter(key => !excludes.has(key))
很好的答案tincot ..只是添加了另一種可能更容易理解的方法。 您可以將json對象轉換為具有屬性名稱和值的數組,然后使用靜態轉換
var data = {'json': [{
'order': 'By',
'name': 'Stack',
'randomkey': '3',
'randomkey_n': '0',
'score': '121',
'id': '540'
}]};
var transform = {"<>": "tr","html":[
{"<>":"td","html":"${val}"}
]};
var _data = [];
for(var i=0; i < data.json.length; i++){
var out = [];
for(var prop in data.json[i])
if(prop !== "id") out[i] = {"name":prop,"val":data.json[i][prop]};
_data.push(out);
}
$('#placar > tbody ').json2html(_data, transform);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.