Open In App
Related Articles

How to print the content of an object in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

To print the content of an object in JavaScript, we have multiple approaches.

Below are the approaches used to print the content of an object in JavaScript:

Approach 1: Using JSON.stringify

The JSON.stringify() method in JavaScript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data in a database or for sending the data to an API or web server. The data has to be in the form of strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() method.

Syntax:

JSON.stringify(value, replacer, space);

Example 1: This example converts the object to a string by simply traversing it and appending the object property and value to the string. 

Javascript

let GFG_object = {
    prop_1: 'val_11',
    prop_2: 'val_12',
    prop_3: 'val_13'
};
 
let printObj = function (obj) {
    let string = '';
 
    for (let prop in obj) {
        if (typeof obj[prop] == 'string') {
            string += prop + ': ' + obj[prop] + '; \n';
        }
        else {
            string += prop + ': { \n' + print(obj[prop]) + '}';
        }
    }
 
    return string;
}
 
console.log(printObj(GFG_object));

                    

Output
prop_1: val_11; 
prop_2: val_12; 
prop_3: val_13; 

Example 2: This example using the JSON.stringify() method to convert the object to string. 

Javascript

let GFG_object = {
    prop_1: 'val_11',
    prop_2: 'val_12',
    prop_3: 'val_13'
};
   
console.log(JSON.stringify(GFG_object));

                    

Output
{"prop_1":"val_11","prop_2":"val_12","prop_3":"val_13"}

Approach 2: Using console.log

To print the content of an object in JavaScript, we could use console.log

Example: Here, we are using console.log statement to print the content of an object in JavaScript.

Javascript

const myObject = { key1: 'value1', key2: 'value2', key3: 'value3' };
 
console.log(myObject);

                    

Output
{ key1: 'value1', key2: 'value2', key3: 'value3' }

Approach 3: Looping through Object Properties

To print the content of an object in JavaScript, we could Loop through Object Properties.

Example: Here, we are Looping through Object Properties to print the content of an object in JavaScript.

Javascript

const myObject = { key1: 'value1', key2: 'value2', key3: 'value3' };
 
for (const key in myObject) {
    if (myObject.hasOwnProperty(key)) {
        console.log(`${key}: ${myObject[key]}`);
    }
}

                    

Output
key1: value1
key2: value2
key3: value3


Last Updated : 16 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads