settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: JSON’s Table - JavaScript task

+4 votes

JSON’s Table is a magical table which turns JSON data into an HTML table. You will be given JSON strings holding data about employees, including their name, position and salary. You need to parse that data into objects, and create an HTML table which holds the data for each employee on a different row, as columns.

The name and position of the employee are strings, the salary is a number.

The input comes as array of strings. Each element is a JSON string which represents the data for a certain employee.

Examples:

Input:
{"name":"Pesho","position":"Promenliva","salary":100000}
{"name":"Teo","position":"Lecturer","salary":1000}
{"name":"Georgi","position":"Lecturer","salary":1000}

Output:

<table>
	<tr>
		<td>Pesho</td>
		<td>Promenliva</td>
		<td>100000</td>
	<tr>
	<tr>
		<td>Teo</td>
		<td>Lecturer</td>
		<td>1000</td>
	<tr>
	<tr>
		<td>Georgi</td>
		<td>Lecturer</td>
		<td>1000</td>
	<tr>
</table>

The output is the HTML code of a table which holds the data exactly as explained above. Check the examples for more info.

asked in JavaScript category by user nikole

1 Answer

+3 votes

The solution:

function printTable(JSONarr) {

    let html = '<table>\n';
    for (let json of JSONarr) {
        let arr = JSON.parse(json);
        html += '	<tr>\n';
        let name = arr.name;
        html += `		<td>${name}</td>\n`;
        let position = arr.position;
        html += `		<td>${position}</td>\n`;
        let salary = arr.salary;
        html += `		<td>${salary}</td>\n`;
        html += '	<tr>\n';
    }

    html += '</table>\n';
    console.log(html);
}
printTable('[{"name":"Pesho","position":"Promenliva","salary":100000},{"name":"Teo","position":"Lecturer","salary":1000},{"name":"Georgi","position":"Lecturer","salary":1000}]');

 

answered by user paulcabalit
...