Javascript 如何在对象中创建键的表标题行?
我从服务器获取一个用户列表作为一个对象数组,然后我想将这个数组转换成一个html表。 问题是我不想预先创建表的标题行,我想从对象的键形成它Javascript 如何在对象中创建键的表标题行?,javascript,html,dom,Javascript,Html,Dom,我从服务器获取一个用户列表作为一个对象数组,然后我想将这个数组转换成一个html表。 问题是我不想预先创建表的标题行,我想从对象的键形成它 fetch('get_url') .then(response => response.json()) .then(data => { obj = data }) .catch(error => console.error(error)) An obj array containing the fo
fetch('get_url')
.then(response => response.json())
.then(data => { obj = data })
.catch(error => console.error(error))
An obj array containing the following objects:
0: {…}
age: "19"
company: "sunplace"
experience: "10"
gender: "male"
lastname: "Parker"
placeofwork: "Airport"
specialty: "cleaner"
username: "Fred"
1: {…}
age: "18"
company: "sunplace"
experience: "10"
gender: "male"
lastname: "Branton"
placeofwork: "Airport"
specialty: "cleaner"
username: "Lar"
2: {…}
age: "20"
company: "sunplace"
experience: "3"
gender: "female"
lastname: "Kollin"
placeofwork: "Airport"
specialty: "cleaner"
username: "Laral"
简短回答:
Object.keys(myUsers[0])
将为您提供第一个元素的键
长答覆:
const myUsers=[{
年龄:"19岁",,
公司:“阳光广场”,
经验:“10”,
性别:“男性”,
姓:“帕克”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Fred”
},
{
年龄:"19岁",,
公司:“阳光广场”,
经验:“10”,
性别:“男性”,
姓:“帕克”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Fred”
},
{
年龄:"19岁",,
公司:“阳光广场”,
经验:“10”,
性别:“男性”,
姓:“帕克”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Fred”
}];
//提取HTML头的值
const header=Object.keys(myUsers[0]);
//创建动态表。
const table=document.createElement(“表”);
//使用上面提取的标题创建HTML表格标题行。
设tr=table.insertRow(-1);//表行。
for(设i=0;i
假设数组中的所有对象都具有相同的结构,这可以通过访问数组中的第一项并使用其键构造表头来实现
const数据=[
{
年龄:"19岁",,
公司:“阳光广场”,
经验:“10”,
性别:“男性”,
姓:“帕克”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Fred”
},
{
年龄:"18岁",,
公司:“阳光广场”,
经验:“10”,
性别:“男性”,
姓:“布兰顿”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Lar”
},
{
年龄:"20岁",,
公司:“阳光广场”,
经验:“3”,
性别:“女性”,
姓:“科尔林”,
工作地点:“机场”,
特色:“清洁剂”,
用户名:“Laral”
}
]
让headers=Object.keys(数据[0])
设thead=document.createElement('thead')
让行=document.createElement('tr')
让createCell=text=>{
设th=document.createElement('th')
text=document.createTextNode(文本)
附加子项(文本)
返回th
}
headers.forEach(header=>{
let cell=createCell(标题)
行。追加子项(单元格)
})
thead.appendChild(行)
document.body.appendChild(thead)
另请参见:是的,情况类似,我错过了,谢谢