'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!
Solution 1:[1]
You can use JSON.stringify to serialize an object and easily log its properties:
console.log(JSON.stringify(car1))
Solution 2:[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.
Solution 3:[3]
You can use
for(aVariable in yourObject){
console.log(aVariable);
}
This way, you can see every attribute of an object
Solution 4:[4]
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>
Solution 5:[5]
Why don't you use Object.keys/Object.values and then suitably adding forEach loop to access the keys/values?
Object.keys(Car).forEach(prop => console.log(prop)) //it will print keys of the the Car object
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...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | agconti |
| Solution 2 | Community |
| Solution 3 | |
| Solution 4 | somethinghere |
| Solution 5 | Rakshit Bhatt |
