Hazelek Hazelek - 25 days ago 9
Javascript Question

object Object issue with display objects

Hey I have a constructor objects in JS and wants to see all of that object, why did pops up [object Object] like here?

.

Answer

You can iterate over all the object keys and populate the new created persArr with the object pers properties values.

Finally in only one call you can get all the properties values properly separated by comma persArr.join(', '):

function Person(first, last, age, eyecolor) {
  this.first = first;
  this.last = last;
  this.age = age;
  this.eyecolor = eyecolor;
}

var pers = new Person('John', 'Colin', 47, 'blue'),
    persArr = [];

Object.keys(pers).forEach(function(key) {
  persArr.push(pers[key]);
});

document.getElementById('data').innerHTML = persArr.join(', ');
#data {
  display: flex;
  width: 120px;
  height: 40px;
  border: 1px solid #000;
  background-color: #fff;
  justify-content: center;
  align-items: center;
}
<div id="data"></div>

If you want to print the object for debugging purposes:

  • Output in console:

    console.log(pers);

  • Output as an string, in the html, by using JSON.stringify():

    document.getElementById('data').innerHTML = JSON.stringify(pers, null, 4);