Print Content of JavaScript Object

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:

screenshot console chrome

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



Leave a reply



Submit