3

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!

Dustin Baker
  • 43
  • 1
  • 1
  • 3

5 Answers5

7

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

console.log(JSON.stringify(car1))
agconti
  • 17,780
  • 15
  • 80
  • 114
2

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.

Community
  • 1
  • 1
Eleanore
  • 1,750
  • 3
  • 16
  • 33
0

Technically, you can use a simple for loop to loop through all the properties, but that means you get all the properties that were set in it's ancestors as well, so you can use Object.hasOwnProperty to verify that this property was set for itself and not inherited, and print out the relevant properties (or do something with them).

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

var bmw = new Car('VW','Cruiser',1989);
var output = document.getElementById('output');

for(property in bmw) 
  if(bmw.hasOwnProperty(property))  
    output.innerHTML += property + ': ' + bmw[property] + '<br />'
<div id="output"></div>
somethinghere
  • 16,311
  • 2
  • 28
  • 42
0

Why don't you use Object.keys/Object.values and then suitably adding forEach loop to access the keys/values?

  1. Object.keys(Car).forEach(prop => console.log(prop)) //it will print keys of the the Car object

  2. Object.values(Car).forEach(prop=>console.log(prop)) // it will print values of the Car object

But it won't give desired output in case of nested Object. So go on with normaml forEach loop or traditional looping method...

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '22 at 14:23
-1

MDN documentation will help

You can use

for(aVariable in yourObject){
   console.log(aVariable);
}

This way, you can see every attribute of an object

Bonatti
  • 2,778
  • 5
  • 23
  • 42
  • This is a duplicate of my answer. – Eleanore Nov 03 '15 at 16:00
  • 1
    yes, this code is common, and we posted very close to each other, however, I have added a source, and even eddited to be closer to what you wrotte.... but both our answers fit the question – Bonatti Nov 03 '15 at 16:01