Q: Score to HTML - JavaScript task

+3 votes

You are given a JSON string representing an array of objects, parse the JSON and create a table using the supplied objects. The table should have 2 columns "name" and "score", each object in the array will also have these keys.

Any text elements must also be escaped in order to ensure no dangerous code can be passed.

You can either write the HTML escape function yourself or use the one from the Strings and Regular Expressions Lab.

The input comes as a single string argument – the array of objects as a JSON.





'[{"name":"Pesho & Kiro","score":479},{"name":"Gosho, Maria & Viki","score":205}]'


  <tr><td>Pesho &amp; Kiro</td><td>479</td></tr>
  <tr><td>Gosho, Maria &amp; Viki</td><td>205</td></tr>

The output should be printed on the console – a table with 2 columns - "name" and "score", containing the values from the objects as rows.

asked in JavaScript category by user andrew

1 Answer

+2 votes

Here is the javascript solution:

function scoreToHTMLTable(scoreJSON) {
    let html = "<table>\n";
    html += "  <tr><th>name</th><th>score</th></tr>\n";
    let arr = JSON.parse(scoreJSON);
    for (let obj of arr) {
        html += `  <tr><td>${htmlEscape(obj['name'])}` +
    console.log(html + "</table>");

    function htmlEscape(text) {
        let map = {
            '"': '&quot;', '&': '&amp;',
            "'": '&#39;', '<': '&lt;', '>': '&gt;'
        return text.replace(/[\"&'<>]/g, ch => map[ch]);

answered by user eiorgert