Exercise - Data Grid (Basic) - SOLVED

by Anup Pradhan

JavaScript

/*
Create a function that accepts an array of similar objects
And will generate a "table" in the console
The header row will be the property names and should display ONCE
The body rows will be the property values
Hint: use tabs to align, "/t" is the tab character
Bonus points for prettying it up

ex output:
Name      Value
Ryan      913
Jimmy     20003
Donna     923
*/

var makeGrid = function (data) {
    
    for (var i = 0; i < data.length; i++) {

        var header = '';
        var row = '';

        for (var propName in data[i]) {
            
            if (data[i].hasOwnProperty(propName)) {

                if (i === 0) {
                    header += propName + "\t\t";
                }
                
                row += data[i][propName] + "\t\t";

            }
        }

        if (header.length > 0) {
            console.log(header);
        }
        
        console.log(row);

    }

};

makeGrid([
    {
        name: "Ryan",
        val: "39",
        colors: ["blue"]
    },
    {
        name: "Jimmy",
        val: "29011",
        colors: ["red", "green"]
    }
]);

// Oh... the humanity
/*
console.table([
    {
        name: "Ryan",
        val: "39",
        colors: ["blue"]
    },
    {
        name: "Jimmy",
        val: "29011",
        colors: ["red", "green"]
    }
]);/**/