skip to Main Content

I need to create a simple table using JavaScript based on an array with nested objects, which should have only two columns. In the first cell of the first column of the table, the Processor header is specified, after which the corresponding processor models are written to the lower cells. In the first cell of the second column, the Processor frequency header is indicated, after which the frequencies are written to the lower cells. I was able to generate code for this task, but it doesn’t work correctly. Instead of writing keys to column cells after the first iteration, for some reason, it takes into account unnecessary objects. That’s why you get an undefined value in the table headers and a re-duplication. Please tell me how to solve this problem.

let processorFrequency = [
    {
        titleOne : 'Processor', values : [
            {name : '80386LC (1988г.)'},
            {name : '80486DX4 (1994г.)'},
            {name : 'Pentium MMX (1997г.)'},
            {name : 'Pentium II (1998г.)'},
            {name : 'Pentium III (1999г.)'},
            {name : 'Pentium IV'},
            {name : 'Athlon-Athlon XP'},
            {name : 'Athlon 64'},

        ]
    },
    {
        titleTwo : 'Processor frequency', values : [
            {name : '33-60'},
            {name : '80-133'},
            {name : '160-233'},
            {name : '260-550'},
            {name : '300-1400'},
            {name : '1600-3800'},
            {name : '1400-3200'},
            {name : '2600-3800'},
        ]
},
]



function Test(){
    let table = document.getElementsByTagName('table')[0];
    for (let i = 0; i < processorFrequency.length; i++) {
        var pf = processorFrequency[i];
        let tableRow = document.createElement('tr');
        let tdOne = document.createElement('td');
        let tdTwo = document.createElement('td');
        let txtOne = document.createTextNode(pf.titleOne);
        let txtTwo = document.createTextNode(pf.titleTwo);
        
        tdOne.className = 'head';
        tdTwo.className = 'head';

        tdOne.appendChild(txtOne);
        tdTwo.appendChild(txtTwo);

        tableRow.appendChild(tdOne);
        tableRow.appendChild(tdTwo);
        table.appendChild(tableRow);

        var values = pf.values;
        for (let j = 0; j < values.length; j++) {
            let value = values[j];
            let tableRow = document.createElement('tr');
            let td = document.createElement('td');
            let txt = document.createTextNode(value.name);
            td.appendChild(txt);
            tableRow.appendChild(td);
            table.appendChild(tableRow);
        }
    }
} 

Test();
table td, table th {
  border: 1px solid black;
  padding: 5px;
}
<table><!-- Contents will be created via JavaScript -->
</table>

3

Answers


  1. Seems like the issue is that you are creating a new row for each processor AND frequency value, which results in extra rows being added to the table. The correct way should be create a single row for each processor, with two cells (one for the processor model and one for the processor frequency):

    let processorFrequency = [
        {
            titleOne: 'Processor', values: [
                { name: '80386LC (1988г.)' },
                { name: '80486DX4 (1994г.)' },
                { name: 'Pentium MMX (1997г.)' },
                { name: 'Pentium II (1998г.)' },
                { name: 'Pentium III (1999г.)' },
                { name: 'Pentium IV' },
                { name: 'Athlon-Athlon XP' },
                { name: 'Athlon 64' },
            ]
        },
        {
            titleTwo: 'Processor frequency', values: [
                { name: '33-60' },
                { name: '80-133' },
                { name: '160-233' },
                { name: '260-550' },
                { name: '300-1400' },
                { name: '1600-3800' },
                { name: '1400-3200' },
                { name: '2600-3800' },
            ]
        },
    ];
    
    function Test() {
        let table = document.getElementsByTagName('table')[0];
    
        for (let i = 0; i < processorFrequency[0].values.length; i++) {
            let tableRow = document.createElement('tr');
            
            // Processor Name Cell
            let tdOne = document.createElement('td');
            let txtOne = document.createTextNode(processorFrequency[0].values[i].name);
            tdOne.appendChild(txtOne);
            tableRow.appendChild(tdOne);
    
            // Processor Frequency Cell
            let tdTwo = document.createElement('td');
            let txtTwo = document.createTextNode(processorFrequency[1].values[i].name);
            tdTwo.appendChild(txtTwo);
            tableRow.appendChild(tdTwo);
    
            table.appendChild(tableRow);
        }
    }
    
    Test();
    
    Login or Signup to reply.
  2. to populate table with columns based on array with nested object , where each object represents processor details , you can follow these steps :

    1. create table element in your HTML file with the appropriate headers
    2. write a javascript code to iterate over the array , extract the processor models and frequencies , and populate the table cells accordingly
    Login or Signup to reply.
  3. Your loops were confused as to where it was in the data structure.

    Since <table> elements are constructed row-by-row, the simplest way is to add row elements in the outer loop:

    let processorFrequency = [
        {
            title : 'Processor', values : [
                {name : '80386LC (1988г.)'},
                {name : '80486DX4 (1994г.)'},
                {name : 'Pentium MMX (1997г.)'},
                {name : 'Pentium II (1998г.)'},
                {name : 'Pentium III (1999г.)'},
                {name : 'Pentium IV'},
                {name : 'Athlon-Athlon XP'},
                {name : 'Athlon 64'},
    
            ]
        },
        {
            title : 'Processor frequency', values : [
                {name : '33-60'},
                {name : '80-133'},
                {name : '160-233'},
                {name : '260-550'},
                {name : '300-1400'},
                {name : '1600-3800'},
                {name : '1400-3200'},
                {name : '2600-3800'},
            ]
    },
    ]
    
    function Test() {
        let table = document.getElementsByTagName('table')[0];
        // Add title row
        let titleRow = document.createElement('tr');
        table.appendChild(titleRow);
        for (let i = 0; i < processorFrequency.length; i++) {
            var columnData = processorFrequency[i];
            let titleCell = document.createElement('td');
            titleCell.className = 'head';
            titleCell.innerText = columnData.title;
            titleRow.appendChild(titleCell);
        }
    
        // Add data rows
        for (let rowIdx = 0; rowIdx < processorFrequency[0].values.length; rowIdx++) {
            let dataRow = document.createElement('tr');
            table.appendChild(dataRow);
            for (let i = 0; i < processorFrequency.length; i++) {
                var columnData = processorFrequency[i];
                let dataCell = document.createElement('td');
                if (columnData.values[rowIdx]) {
                    dataCell.innerText = columnData.values[rowIdx].name;
                }
    
                dataRow.appendChild(dataCell);
            }
        }
    }
    
    Test();
    table td, table th {
      border: 1px solid black;
      padding: 5px;
    }
    <table><!-- Contents will be created via JavaScript -->
    </table>

    It might make the code simpler if you organized the data by row:

    let processorFrequencyRows = [
        ['Processor',                      'Processor frequency'],
        ['80386LC (1988г.)',               '33-60'],
        ['80486DX4 (1994г.)',              '80-133'],
        ['Pentium MMX (1997г.)',           '160-233'],
        ['Pentium II (1998г.)',            '260-550'],
        ['Pentium III (1999г.)',           '300-1400'],
        ['Pentium IV',                     '1600-3800'],
        ['Athlon-Athlon XP',               '1400-3200'],
        ['Athlon 64',                      '2600-3800'],
    ];
    
    function Test() {
        let table = document.getElementsByTagName('table')[0];
        processorFrequencyRows.forEach((rowData) => {
            let row = document.createElement('tr');
            table.appendChild(row);
            rowData.forEach((cellText) => {
                let cell = document.createElement('td');
                cell.innerText = cellText;
                row.appendChild(cell);
            });
        });
    }
    
    Test();
    table td, table th {
      border: 1px solid black;
      padding: 5px;
    }
    <table><!-- Contents will be created via JavaScript -->
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search