1

I want to create a table whose header labels are known dynamically based on data object property names

Here is my code example:

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;
}
laurent
  • 2,590
  • 18
  • 26
MrDevIll
  • 21
  • 6
  • 3
    The title hurts – Jonas Wilms Dec 27 '17 at 11:11
  • 1
    And yes its possible, however this is the worst thing you can do. Whywould you need that? – Jonas Wilms Dec 27 '17 at 11:13
  • what title would you use? – MrDevIll Dec 27 '17 at 11:13
  • 5
    Why would you want separate variables when you already have the data neatly inside an object? – JJJ Dec 27 '17 at 11:16
  • the data above is only a part of an object I extracted it for the question. I know how to create the "th" head without loop I wish to understand if there is any syntax in es6 that allows me to do what I try to do in the example. thanks – MrDevIll Dec 27 '17 at 11:26
  • 1
    No there is no real syntax for it as there is no real usecase for that – Jonas Wilms Dec 27 '17 at 11:28
  • 1
    This seems to be an [XY problem](http://xyproblem.info). If you want to generate a table from the object, you don't need temporary variables that each have a different name. Maybe show your code and ask how to solve the *actual* problem. – JJJ Dec 27 '17 at 11:29
  • 1
    Considering that `let` is being scoped to each loop iteration, why on earth would you want to create 3 differently named variables? Surely they can have the same name, because they'll very soon be out of scope – user184994 Dec 27 '17 at 11:29
  • I believe you want to look up the data object property names to dynamically create header labels ? If so, maybe you can use Object.keys(yourObj) – laurent Dec 27 '17 at 11:30
  • @laurent thank you I think is what I wa looking for! : ) – MrDevIll Dec 27 '17 at 11:36
  • @user184994 good point, yes I dont' really need to create a dynamic var in this code. thank you for pointing out – MrDevIll Dec 27 '17 at 11:41

1 Answers1

0

You could try 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>
HMR
  • 37,593
  • 24
  • 91
  • 160