0

I'm having variable with some properties:

var fullName = { FirstName:'Josef',SecondName:'Luis', LastName:'Pumpkin'}

and I'm getting value of this variable and put it into Table like this:

for(var i in fullName){
  if(fullName.hasOwnProperty(i)){
   var newCell = newRow.insertCell(0);
   newCell.innerHTML = fullName[i];
  }
}

The output result is: Josef Luis Pumpkin. The question is how can I add their property name too, to get output like: FirstName - Josef, SecondName - Luis, LastName - Pumpkin (in their cells respectively)?

Ritesh Jagga
  • 1,033
  • 8
  • 21

2 Answers2

3

I'm having variable with some parameters

The variable refers to an object with properties (not parameters).

You have the name of the property in the loop (as i). Just use string concatenation:

newCell.innerHTML = i + " - " + fullName[i];

Or in modern (ES2015+) environments, you could use a template literal:

newCell.innerHTML = `${i} - ${fullName[i]}`;

Beware that the order the properties are visited by for-in is not guaranteed, not even in ES2015+. And even if for-in were specified to support the order that ES2015 does add to properties, that order varies depending on how the object is created. So just note that the cells you're creating may not be consistently in the same order.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1
 i + " - " + fullName[i]

Its just some string concatenation, you already got the key in the i variable. How I would write that:

 Object.entries(fullName)
   .map(pair => pair.join(" - "))
   .forEach(entry => newRow.insertCell(0).innerHTML = entry)
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120