How to print object values correctly to a DIV using innerHTML?

10,030

Solution 1

but it instead of printing out the details of the chosen object, it just prints "[object Object]",

This is because frndLst[onefrnd] is an object and its toString method will print [object Object].

Either use JSON.stringify(frndLst[onefrnd]) to see JSON representation of this object

Or, replace this line

document.getElementById("myfrndDetails").innerHTML = frndLst[onefrnd];

by

document.getElementById("myfrndDetails").innerHTML = "lastname - " +  frndLst[onefrnd].lastName + " and phoneNumber " + frndLst[onefrnd].phoneNumber ;

Solution 2

Change your function like this :

var frndCard = function(frndName,frndLst) {
    for (var onefrnd in frndLst) {
        
        if (frndLst[onefrnd].firstName === frndName) {
            var output = '';
            for (property in frndLst[onefrnd]) {
                output += property + ': ' + frndLst[onefrnd][property]+"; <br>\n";
              }
            document.getElementById("myfrndDetails").innerHTML = output;
            return frndLst[onefrnd];
        }
    }
};

Share:
10,030
theAussieGuy
Author by

theAussieGuy

Updated on June 22, 2022

Comments

  • theAussieGuy
    theAussieGuy about 2 years

    I'm doing a course at Codecademy and many of their beginner courses use the console.log() command to print to the console. I however would like to try using document.GetElementById() and innerHTML but it instead of printing out the details of the chosen object, it just prints "[object Object]", whereas console.log() prints the details of the key?

    Here is my code:

    <div id="myfrndDetails"></div>
    
    <script>
    var frnds = new Object();
    frnds.bill = {
        firstName: "Bill",
        lastName: "Gates",
        phoneNumber: "8778787"
    }
    
    frnds.steve = {
        firstName: "Bill",
        lastName: "Gates",
        phoneNumber: "8778787"
    }
    
    
    var frndCard = function(frndName,frndLst) {
        for (var onefrnd in frndLst) {
            if (frndLst[onefrnd].firstName === frndName) {
                document.getElementById("myfrndDetails").innerHTML = frndLst[onefrnd];
                return frndLst[onefrnd];
            }
        }
    };
    
    frndCard("Bill",frnds);
    
    </script>