Use the DOM APIs

For performance avoid adding markup (HTML) to the page via JavaScript. The DOM APIs are much faster and can be abstracted to make more readable code (DOM APIs are very verbose).

Source complexity

Your solution is convoluted and hard to read. It looks like you tackled the whole problem in one big step. More than a dozen lines of code should be seen as more than one problem to solve.

To solve complex or multi step problem break them into smaller single role parts.

  • Find all rows names

  • Find all columns names

  • Find value by row column name

  • Create DOM elements

  • Append a DOM elements

  • Create a table.

Each of these sub problems can then be solved by defining a function. When you have all the functions you can solve the main problem by combining the sub problems.

Try to make the functions generic. Property names should be dynamic so that you need only minor changes when the data changes. The example show 4 tables, to change your code to provide the different tables would take a lot more work than adding 3 more calls to the main function.

Example

The rewrite breaks the problem into the pars described above. The title, and the names of the row and column properties are passed to the function.

You can see the flexibility of this approach as the table can easily be rotated and transformed by changing the argument order and properties to use for columns and rows.

const notes = [{note: "n1", subject: "subject1", value: 10 }, {note: "n2", subject: "subject2", value: 15 }, {note: "n2", subject: "subject2", value: 5 }, {note: "n3", subject: "subject2", value: 20 }];

const tag    = (tagName, props = {}) => Object.assign(document.createElement(tagName), props);
const txtTag = (tagName, str, props = {}) => tag(tagName, {textContent: str, ...props});
const append = (el, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), el);

append(document.body, 
  createTable("Subjects", "note", "subject", "value", notes),
  createTable("Notes", "subject", "note", "value", notes),
  createTable("Notes", "value", "note", "value", notes),
  createTable("Values", "subject", "value", "value", notes));

function createTable(title, colKey, rowKey, valKey, data) {
  const byKey = key => [...new Set(data.map(rec => rec[key]))];
  const byRowCol = (row, col) => data.reduce((val, rec) => 
    val + (rec[rowKey] === row && rec[colKey] === col ? rec[valKey] : 0), 0);
  const rows = byKey(rowKey), cols = byKey(colKey);
  return append(tag("table"),
    append(tag("tbody"),
      append(tag("tr"),
        txtTag("th", title),
        ...cols.map(str => txtTag("th", str))
      ),
      ...rows.map(row => 
        append(tag("tr"),
          txtTag("th", row),
          ...cols.map(col => txtTag("td", byRowCol(row, col)))
        )
      )
    )
  )
}
* {font-family: arial}
table, tr, th, td {
  border-collapse: collapse;
  border: 1px solid;
  padding: 3px 10px;
  margin: 4px;
}

Answer from Blindman67 on Stack Exchange
🌐
Medium
medium.com › wdstack › quick-blurb-generating-a-table-from-an-array-in-javascript-41386fd449a9
Quick Blurb: Generating a Table from an Array in JavaScript | by Zak Frisch | WDstack | Medium
January 24, 2017 - //setup our table array var tableArr = [ ["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"] ]//create a Table Object let table = document.createElement('table');//iterate over every array(row) within tableArr for (let row ...
Top answer
1 of 4
8

Use the DOM APIs

For performance avoid adding markup (HTML) to the page via JavaScript. The DOM APIs are much faster and can be abstracted to make more readable code (DOM APIs are very verbose).

Source complexity

Your solution is convoluted and hard to read. It looks like you tackled the whole problem in one big step. More than a dozen lines of code should be seen as more than one problem to solve.

To solve complex or multi step problem break them into smaller single role parts.

  • Find all rows names

  • Find all columns names

  • Find value by row column name

  • Create DOM elements

  • Append a DOM elements

  • Create a table.

Each of these sub problems can then be solved by defining a function. When you have all the functions you can solve the main problem by combining the sub problems.

Try to make the functions generic. Property names should be dynamic so that you need only minor changes when the data changes. The example show 4 tables, to change your code to provide the different tables would take a lot more work than adding 3 more calls to the main function.

Example

The rewrite breaks the problem into the pars described above. The title, and the names of the row and column properties are passed to the function.

You can see the flexibility of this approach as the table can easily be rotated and transformed by changing the argument order and properties to use for columns and rows.

const notes = [{note: "n1", subject: "subject1", value: 10 }, {note: "n2", subject: "subject2", value: 15 }, {note: "n2", subject: "subject2", value: 5 }, {note: "n3", subject: "subject2", value: 20 }];

const tag    = (tagName, props = {}) => Object.assign(document.createElement(tagName), props);
const txtTag = (tagName, str, props = {}) => tag(tagName, {textContent: str, ...props});
const append = (el, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), el);

append(document.body, 
  createTable("Subjects", "note", "subject", "value", notes),
  createTable("Notes", "subject", "note", "value", notes),
  createTable("Notes", "value", "note", "value", notes),
  createTable("Values", "subject", "value", "value", notes));

function createTable(title, colKey, rowKey, valKey, data) {
  const byKey = key => [...new Set(data.map(rec => rec[key]))];
  const byRowCol = (row, col) => data.reduce((val, rec) => 
    val + (rec[rowKey] === row && rec[colKey] === col ? rec[valKey] : 0), 0);
  const rows = byKey(rowKey), cols = byKey(colKey);
  return append(tag("table"),
    append(tag("tbody"),
      append(tag("tr"),
        txtTag("th", title),
        ...cols.map(str => txtTag("th", str))
      ),
      ...rows.map(row => 
        append(tag("tr"),
          txtTag("th", row),
          ...cols.map(col => txtTag("td", byRowCol(row, col)))
        )
      )
    )
  )
}
* {font-family: arial}
table, tr, th, td {
  border-collapse: collapse;
  border: 1px solid;
  padding: 3px 10px;
  margin: 4px;
}

2 of 4
4

A short review;

  • JS should be lowerCamelCase, so make_matrix -> makeMatrix
  • array_objs should probably be just be objects
  • I am not a big fan of HTML in JS, consider using a template
  • In makeMatrix you both convert the data into a new structure and build the output, I would split this across 2 functions
  • I see a tendency to name variables more after what they are than what they contain, I hope my counter-examples shows what I mean
  • I find your code very dense and hard to read
  • However I really like the trick to create subjects and notes, will steal that ;)

let notes = [
  { note: "n1", subject: "subject1", value: 10 },
  { note: "n2", subject: "subject2", value: 15 },
  { note: "n2", subject: "subject2", value: 5 },
  { note: "n3", subject: "subject2", value: 20 },
];

function restructureSubjectScores(subjectScores){
  const out = {};
  for(const score of subjectScores){
    out[score.subject] = out[score.subject] || {};
    out[score.subject][score.note] = score.value;
  }
  return out;
}

function buildTable(noteScores){
  const subjects = [...new Set(noteScores.map(({ subject }) => subject))];
  const notes = [...new Set(noteScores.map(({ note }) => note))];
  
  const tableData = restructureSubjectScores(noteScores);  
  const table = document.getElementById('tableTemplate').content.firstElementChild.cloneNode(true);
  
  const header = table.querySelector('thead tr');
  header.innerHTML += notes.map(column => `<th>${column}</th>`).join("");
  
  const tbody = table.querySelector("tbody");
  const rowTemplate = document.getElementById('rowTemplate').content.firstElementChild;

  for(const subject of subjects){
    const row = rowTemplate.cloneNode(true);
    row.querySelector("th").textContent = subject;

    for(const note of notes){
      row.innerHTML += `<td>${tableData[subject][note] || 0}</td>`;
    }
    tbody.appendChild(row);
  }
  return table;
}

document.querySelector(".content").appendChild(buildTable(notes));
table {
  border-collapse: collapse;
  border: 1px solid;
}
tr,
th,
td {
  border: 1px solid;
  padding: 3px 10px;
}
<div class="content"></div>
<template id="tableTemplate">
<table>
  <thead><tr>
    <th class="subject">Subjects</th>
  </tr></thead>
  <tbody>
  </tbody>
</table>
</template>

<template id="rowTemplate">
  <tr>
    <th class="subject"></th>
  </tr>
</template>

🌐
Code.mu
code.mu › en › javascript › book › prime › dom › practice › table-creating-via-objects-array
Creating an HTML table from an array of objects in JavaScript
<table id="table"></table> let table = document.getElementById('table'); for (let user of users) { let tr = document.createElement('tr'); let td1 = document.createElement('td'); td1.textContent = user.name; tr.appendChild(td1); let td2 = document.createElement('td'); td2.textContent = user.surname; tr.appendChild(td2); let td3 = document.createElement('td'); td3.textContent = user.patronymic; tr.appendChild(td3); table.appendChild(tr); }
🌐
YouTube
youtube.com › watch
How to Create Table From an Array of Objects in Javascript - YouTube
In this tutorial, you will learn how to create a table from an array of objects using JavaScript. If you're new to web development or just starting out with ...
Published   March 5, 2020
🌐
DEV Community
dev.to › frankwisniewski › create-table-from-array-of-objects-in-one-line-of-code-c57
create table from array of objects in one line of code - DEV Community
June 5, 2022 - #html #javascript · <html lang=de> <meta charset=UTF-8> <title>Document</title> <link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css"> <body class=container> <h1>Array of objects to table</h1> <script> let cities = [ {"city": "Berlin","country": "Germany"}, {"city": "Paris","country": "France"}] document.querySelector('h1').insertAdjacentHTML('afterend', `<table><thead><tr><th> ${Object.keys(cities[0]).join('<th>')} </thead><tbody><tr><td>${cities.map(e=>Object.values(e) .join('<td>')).join('<tr><td>')}</table>`) </script> Subscribe ·
🌐
Fwait
fwait.com › home › how to create table from an array of objects in javascript
How to Create Table From an Array of Objects in Javascript - Collection of Helpful Guides & Tutorials!
August 10, 2024 - let btnGet = document.querySelector('button'); let myTable = document.querySelector('#table'); let employees = [ { name: 'James', age: 21, country: 'United States' }, { name: 'Rony', age: 31, country: 'United Kingdom' }, { name: 'Peter', age: 58, country: 'Canada' }, { name: 'Marks', age: 20, country: 'Spain' } ] let headers = ['Name', 'Age', 'Country']; btnGet.addEventListener('click', () => { let table = document.createElement('table'); let headerRow = document.createElement('tr'); headers.forEach(headerText => { let header = document.createElement('th'); let textNode = document.createTextNo
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-an-html-table-from-an-object-array-using-javascript
How to Create an HTML Table from an Object Array Using JavaScript ? | GeeksforGeeks
April 28, 2025 - To build an HTML table using ReactJS from arrays we can use the array methods to iterate to iterate the elements and create the table rows Prerequisites:NPM & Node.jsReact JSJavaScript Array.map()HTML TableApproach: To build an HTML table from ...
🌐
Linux Hint
linuxhint.com › create-table-from-array-objects-javascript
How to Create Table From an Array of Objects in JavaScript
October 9, 2022 - In JavaScript, for the formation of a table from an array of objects, the HTML “table” string or “map()” method can be utilized. To do so, specify a div tag with an id. Then, declare the array of objects in both methods, store table tags within variables, or directly return them to ...
Find elsewhere
🌐
Code Boxx
code-boxx.com › home › 2 ways to create table from array in javascript
2 Ways To Create Table From Array In Javascript
January 11, 2024 - This beginner's tutorial will show how to create table from array in Javascript using 2 different methods. Example code download included.
Top answer
1 of 5
6

Two issues at first:

  1. Is that Name or Nome? Please fix your typo (I know Nome is French, so if it's not typo, I suggest you introduce an i18n solution).
  2. Also please mind your syntax errors (some have given suggested edits that you could consider).

After that, here's my approach for programmatically create tables based on input data:

function buildTable(labels, objects, container) {
  var table = document.createElement('table');
  var thead = document.createElement('thead');
  var tbody = document.createElement('tbody');

  var theadTr = document.createElement('tr');
  for (var i = 0; i < labels.length; i++) {
    var theadTh = document.createElement('th');
    theadTh.innerHTML = labels[i];
    theadTr.appendChild(theadTh);
  }
  thead.appendChild(theadTr);
  table.appendChild(thead);

  for (j = 0; j < objects.length; j++) {
    var tbodyTr = document.createElement('tr');
    for (k = 0; k < labels.length; k++) {
      var tbodyTd = document.createElement('td');
      tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
      tbodyTr.appendChild(tbodyTd);
    }
    tbody.appendChild(tbodyTr);
  }
  table.appendChild(tbody);

  container.appendChild(table);
}

var labels1 = ['ID', 'Name']; 
var objects1 = [
  {"id": "1", 'name': "richard"},
  {"id": "2", 'name': "santos"}
];

var labels2 = ['ID', 'NOME'];
var objects2 = [
  {"id": "1", 'nome': "richard"},
  {"id": "2", 'nome': "adriana"}
];

var labels3 = ['ID', 'NAME', 'PLATE'];
var objects3 = [
  {"id": "1", 'name': "jetta",  'plate': "DFG-1222"},
  {"id": "2", 'name': "fusion", 'plate': "DFF-3342"}
];

buildTable(labels1, objects1, document.getElementById('a'));
buildTable(labels2, objects2, document.getElementById('b'));
buildTable(labels3, objects3, document.getElementById('c'));
table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
}
<div id="a"><p>Table 1</p></div>
<div id="b"><p>Table 2</p></div>
<div id="c"><p>Table 3</p></div>

2 of 5
4

This is a working procedure from our project. It has three parameters:

htmlTable(selector, data_array [, column_names]);

column_names parameter is optional: if you omit it the function creates column names from first row (if it exists).

It creates HTML tags directly into the DOM, but it can be rewritten to generate HTML as a string if you need . See the working snippet below:

var labels = ['id','name']; 
var object = [{"id":"1",'name': "richard"},{"id":"2",'name': "santos"}];
htmlTable("#res0",object, labels);

var labels = ['id','nome']; 
var object = [{"id":"1",'nome': "richard"},{"id":"2",'nome': "adriana"}];
htmlTable("#res1",object, labels);

var labels = ['id','name', 'plate']; 
var object = [{"id":"1",'name': "jetta",'plate': "DFG-1222"},
              {"id":"2",'name': "fusion",'plate': "DFF-3342"}];
htmlTable("#res2",object, labels);

// Without labels array
var data3 = [{a:1,c:2},{a:3,c:3}];
htmlTable("#res3",data3);

function htmlTable(selector, data, columns) {
	var sel = document.querySelector(selector);
	if(!sel) {
		throw new Error('Selected HTML element is not found');
	};	

	if((!columns) || columns.length == 0) {
        columns = Object.keys(data[0]);
	}

	var tbe = document.createElement('table');
	var thead = document.createElement('thead');
	tbe.appendChild(thead);

  var tre = document.createElement('tr');
  for(var i=0;i<columns.length;i++){
    var the = document.createElement('th');
    the.textContent = columns[i];
    tre.appendChild(the);
  }
  thead.appendChild(tre);

	var tbody = document.createElement('tbody');
	tbe.appendChild(tbody);
	for(var j=0;j<data.length;j++){
		var tre = document.createElement('tr');
		for(var i=0;i<columns.length;i++){
			var the = document.createElement('td');
			the.textContent = data[j][columns[i]];
			tre.appendChild(the);
		}
		tbody.appendChild(tre);
	};
	emptyDOMChildren(sel);
	sel.appendChild(tbe);
};

// Utility function to fast delete all children of element if it is not empty
// Can be replaced with simple but relatively "slower" container.innerHTML = "";
function emptyDOMChildren (container){
  var len = container.childNodes.length;
  while (len--) {
    container.removeChild(container.lastChild);
  };
};
<div id="res0"></div>
<div id="res1"></div>
<div id="res2"></div>
<div id="res3"></div>

🌐
javaspring
javaspring.net › blog › create-html-table-from-javascript-object
How to Create an HTML Table from a JavaScript Object Array (with Auto-Incrementing ID, Name & Relevance Columns) for Beginners — javaspring.net
In this tutorial, we’ll walk through creating a dynamic HTML table from a JavaScript object array. We’ll include auto-incrementing IDs (to uniquely identify each row), Name, and Relevance columns. By the end, you’ll understand how to dynamically generate tables, manipulate the DOM, and style your table for readability—no prior advanced JavaScript experience required! ... Basic knowledge of HTML (e.g., tags, elements, and the DOM).
🌐
YouTube
youtube.com › watch
How to Create an HTML Table from an Array of Objects - YouTube
Learn how to dynamically create an HTML table using JavaScript from an array of objects. This guide includes step-by-step instructions and CSS styling tips f...
Published   April 16, 2025
Views   8
🌐
CSS Script
cssscript.com › home › categories › table › javascript array/object to table generator – vanillajs-table
JavaScript Array/Object To Table Generator - vanillajs-table | CSS Script
June 12, 2020 - var eats = [ ['Apple', 'Banana', 'Orange', 'Blackberry'], ['Cabbage', 'Turnip', 'Radish', 'Carrot'] ]; var options = { element: document.getElementById("table"), data: eats }; var table = new Table(options); table.view(); var discography = [ { album: "MCMXC a.D.", year: 1990 }, { album: "The Cross of Changes", year: 1993 } ]; var options = { element: document.getElementById("table"), data: discography }; var table = new Table(options); table.view();
🌐
YouTube
youtube.com › coding comics
Table in React Js || Create Table from Array of Objects in React Js - YouTube
In this video, I have explained how to create a table using array of object in react js.code : (https://github.com/AkajithAk/ReactUiYt/tree/main/src/ReactTab...
Published   February 4, 2023
Views   4K
Top answer
1 of 1
2

TL;DR Fully functionnal example :

//Columns defines table headings and properties to be placed into the body
const columns = [{ heading: 'Name', property: 'name' }, { heading: 'Age', property: 'age' }, { heading: 'Sex', property: 'sex' }, { heading: 'Breed', property: 'breed' },]

//Data is the array of objects to be placed into the table
const data = [{ name: 'Sabrina', age: '6', sex: 'Female', breed: 'Staffordshire' }, { name: 'Max', age: '2', sex: 'Male', breed: 'Boxer' }]

const App = props => <Table columns={columns} data={data} propertyAsKey='name' />

const Table = ({ columns, data, propertyAsKey }) => 
    <table className='table'>
        <thead>
            <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
        </thead>
        <tbody>
            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}</td>)}
                </tr>
            )}
        </tbody>
    </table>
    
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id='root'>


The main thing that would highly reduce this code is the map function. This function can be applied on an array, execute a callback on every item in the array and returns a new array.

By using it you can reduce the following code :

let headerRow = [];

columns.forEach(col => {
    headerRow.push(
        <th key={`header-${col.heading}`}>{col.heading}</th>
    );
});

Can be reduced to this with the exact same result :

const headerRow = columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)

You can now include this function directly into your JSX :

<thead>
    <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
</thead>

And the same thing with nested mapping for the body :

<tbody>
    {data.map(item => 
        <tr key={`${item[key]}-row`}>
            {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}</td>)}
        </tr>
    )}
</tbody>

Your full buildTable function is now reduced to the following :

buildTable = (columns, data, key) => {
    return (
        <>
            <thead>
                <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
            </thead>
            <tbody>
                {data.map(item => 
                    <tr key={`${item[key]}-row`}>
                        {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}</td>)}
                    </tr>
                )}
            </tbody>
        </>
    );
};

If you want to go a little further you can also delete this function and embed this code in your render function JSX. I will also convert your component into a stateless function, since you are not using any state value :

const Table = ({ columns, data, propertyAsKey }) => //Deconstructs your props
    <table className='table'>
        <thead>
            <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
        </thead>
        <tbody>
            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}</td>)}
                </tr>
            )}
        </tbody>
    </table>

(You may add brackets and a return statement after the arrow sign, its up to you)

It is also not required to have a fragment as a parent element in your render, as long as there is a single element, it is fine :

class App extends React.Component {
  render() {
    return (
        <Table
          columns={columns}
          data={data}
          propertyAsKey='name' //The data property to be used as a key
        />
    );
  }
}

Your App component could also be converted to a stateless component:

const App = props => <Table columns={columns} data={data} propertyAsKey='name' />
🌐
DocStore
docstore.mik.ua › orelly › webprog › DHTML_javascript › 0596004672_jvdhtmlckbk-chp-14-sect-8.html
14.7 Transforming JavaScript Objects into HTML Tables
You want to render embedded JavaScript data as an HTML table · When JavaScript data is formatted as an array of objects, it is a relatively simple job to use the data to drive the creation of rows and cells of an HTML table. Here is an example of some repetitive data assembled on the server ...
🌐
YouTube
youtube.com › coding wall
Display array of objects using #javaScript and #HTML | populate html table with json data - YouTube
Display #array of #object data using #javaScript and #HTML.#populate #html #table with #json #datadisplaying a array of objects with key values using html an...
Published   October 16, 2021
Views   27K
Top answer
1 of 9
20

Explanation

What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.

You want to loop through the object. The best way to do so would be with a for loop, and making sure our looping variable remains valid for the length of our object (all its attributes).

The best way to get the length of a JSON object is through myJSONObject.length: You select the keys of myJSONObject and return their count.

You can access the values stored in your JSON Object the following way, in your for loop (assuming the looping variable defined is named i): myJSONObject[i].theAttributeIWantToGet


Price formatting breakdown

Now, those prices need to have a proper format, don't they? So we'll check if any of the value attribute has less than 2 characters after the . within them. If they do, we add another decimal 0. We also add a $ before writing the formatted value. Here is a breakdown of how it works:

  • obj[i].value.toString().substring(startIndex, length)

    • We want to check the length after the . sign, so our startIndex will be the position of this dot within our string.
    • obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
    • We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
    • Final result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2

      • This will return true or false. If it's true: There's less than 2 digits after the dot !
    • We add the if statement and the last zero:

    • if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) obj[i].value += "0";

Also: Why I use innerHTML instead of appendChild().


Solution

JSFiddle

HTML

<table>
    <tbody id="tbody"></tbody>
</table>

JSON

[{
    "key": "apple",
    "value": 1.90
}, {
    "key": "berry",
    "value": 1.7
}, {
    "key": "banana",
    "value": 1.5
}, {
    "key": "cherry",
    "value": 1.2
}]

JavaScript

Note: The JSON object will be named obj in this instance.

var tbody = document.getElementById('tbody');

for (var i = 0; i < obj.length; i++) {
    var tr = "<tr>";

    /* Verification to add the last decimal 0 */
    if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2) 
        obj[i].value += "0";

    /* Must not forget the $ sign */
    tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";

    /* We add the table row to the table body */
    tbody.innerHTML += tr;
}

JSFiddle

2 of 9
8

It can be simply done by a small & smart process:

<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
    <tr>
        <th>Name</th>
        <th width="20%">Age</th>
        <th width="12%">Status</th>
    </tr>
</thead>
    <tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
    var mainObj = [
        {
            name: "Kapil",
            age:  21,
            status: "Active"
        },
        {
            name: "John",
            age:  28,
            status: "Inactive"
        },
        {
            name: "Deos",
            age:  18,
            status: "Active"
        }
    ];
    var k = '<tbody>'
    for(i = 0;i < mainObj.length; i++){
        k+= '<tr>';
        k+= '<td>' + mainObj[i].name + '</td>';
        k+= '<td>' + mainObj[i].age + '</td>';
        k+= '<td>' + mainObj[i].status + '</td>';
        k+= '</tr>';
    }
    k+='</tbody>';
    document.getElementById('tableData').innerHTML = k;
    </script>