Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all properties/values in an object at once. JS

So let's say that I have this:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var car1 = new Car("VW", "Bug", 2012);
var car2 = new Car("Toyota", "Prius", 2004);

document.write(car1.make, car1.model, car1.year);
document.write(car2.make, car2.mocel, car2.year);

Is there a cleaner way to write out all of the properties/values of objects? Thank!

like image 692
Dustin Baker Avatar asked Oct 27 '25 16:10

Dustin Baker


2 Answers

You can use JSON.stringify to serialize an object and easily log its properties:

console.log(JSON.stringify(car1))
like image 87
agconti Avatar answered Oct 30 '25 07:10

agconti


To enumerate all the properties of an object in JavaScript:

for (aProperty in yourObject) {
    // do what needed
    // in case you want just to print it:
    console.log(aProperty + "has value: " + yourObject[aProperty]);
}

However, if you just meant to print the object to the console, maybe this question can help you.

like image 23
Eleanore Avatar answered Oct 30 '25 08:10

Eleanore