Search code examples
jqueryhtmlarraysjavascript-objects

Appending an object list with arrays within it's values


I am trying to display a list of objects in a table. But I am getting undefined values back. I have objects within objects and I can't seem to get it to work.

My objects

var names = {
  fname : {"Bill", "John"},
  lname : {"Smith", "Evans"},
  age : {"30", "41"}
}

I tried a for loop but with no luck

for (i in names){
  $("#myTable").append("<tr><td>" + names[i].fname +", "+ names[i].lname +"</td>"+
"<td>"+ names[i].age +"</td></tr>"
);
}

my table

<table>
 <tbody id="myTable">
  <tr>
   <th>Name</th>
   <th>Age</th>
  </tr>
 </tbody>
</table>

My goal is to append new entries to the objects list directly into the html table, based on the index of each value.


Solution

  • There are two issues. First, your input data is invalid:

    var names = {
      fname : {"Bill", "John"},
      lname : {"Smith", "Evans"},
      age : {"30", "41"}
    }
    

    Assuming each of these should be an array? For example: fname: ["Bill", "John" ].

    Second, you're looping through each key of the object (fname, lname, age). Assuming you want to loop through each value of each key?

    As long as all the keys will always have the same length, you can choose the first fname attribute and loop from 0 to one less than the total length.

    var names = {
      fname: [
        "Bill",
        "John"
      ],
      lname: [
        "Smith",
        "Evans"
      ],
      age: [
        "30",
        "41"
      ]
    }
    
    for (var i = 0; i < names.fname.length; i++) {
      $("#myTable").append("<tr><td>" + names.fname[i] + ", " + names.lname[i] + "</td>" +
        "<td>" + names.age[i] + "</td></tr>"
      );
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody id="myTable">
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </tbody>
    </table>