如何获取javascript对象属性名称?

时间:2017-12-27 11:10:07

标签: javascript variables html-table ecmascript-6

我想创建一个表,其标题标签是基于数据对象属性名称

动态获知的

这是我的代码示例:

ob = { ** name **: "Joe",
  ** age **: "22",
  ** country **: "UK"
}

table = document.createElement("table");

function createHeaders(obj) {
  let tr = document.createElement("tr");
  //get keys and iterate ...
  for (let key of keys) {// how to get keys ? 
    const th = document.createElement('th');
    th.innerHtml = key;
    tr.appendChild(th)
  }
  return tr;
}

1 个答案:

答案 0 :(得分:0)

您可以尝试Object.keys

function createHeader(object) {
  return Object.keys(object)
  .reduce(
    (tr,key)=>{
      tr.appendChild(
        document.createElement("th")
      ).innerHTML = key;
      return tr;
    },
    document.createElement("tr")
  );
};
const table = document.createElement("table");
table.appendChild(
  createHeader({ 
    name: "Joe",
    age: "22",
    country: "UK"
  })
);
document.getElementById("content").appendChild(table);
<div id="content"></div>