Print content of JavaScript object?
If you are using Firefox, alert(object.toSource())
should suffice for simple debugging purposes.
How can I display a JavaScript object?
If you want to print the object for debugging purposes, use the code:
var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
will display:
Note: you must only log the object. For example, this won't work:
console.log('My object : ' + obj)
Note ': You can also use a comma in the log
method, then the first line of the output will be the string and after that, the object will be rendered:
console.log('My object: ', obj);
Why we cant use normal for loop to print javascript object?
As opposed to for... of
, the for... in
loop will iterate over the enumerable properties (not their values) of an object.
In your example above, you're iterating over the keys of the object (the "properties labels"), and then using them to access the values on object1
.
The example below will demonstrate more clearly how the for... in
loop works.
const arr = [23, 45, 67, 56];
for(let index in arr) {
// Note that only the indexes of the array are
// assigned to 'index', not the values
console.log('Index:', index);
// To access the values, you should do:
console.log('Value:', arr[index])
}
How can I pretty print keys and values of a JavaScript object on web page
Us Object.entries and map to format the data how you want to display it.
let dict = {
term1: "definition 1",
term2: "definition 2",
term3: "definition 3",
term4: "definition 4"
}
const str = Object.entries(dict).map(([key, value]) => `${key}: ${value}`).join("<br/>");
document.getElementById("out").innerHTML = str;
<div id="out"></div>
Related Topics
Caching a Promise Object in Angularjs Service
Tolocaledatestring() Changes in Ie11
How to Set Locale in Datepipe in Angular 2
How to Compare Two Time Strings in the Format Hh:Mm:Ss
Do Something If Screen Width Is Less Than 960 Px
Using Jquery to Replace One Tag with Another
How to Trigger the Window Resize Event in JavaScript
How to Select Option in Drop Down Protractorjs E2E Tests
Cross-Origin Read Blocking (Corb)
How to Set Default Homepage in Ff and Chrome via JavaScript
Checking If Jquery Is Loaded Using JavaScript
Check If All Values of Array Are Equal
Adding Custom Functions into Array.Prototype
How to Find the Height of Text on an HTML Canvas
Chrome Refuses to Execute an Ajax Script Due to Wrong Mime Type