How can you map the differences between Javascript objects?

How can one inspect JavaScript objects?

  • In PHP for instance there is print_r() to inspect objects. How can one inspect the properties of a JavaScript object? When printing the object to the console the output is only [object Object].

  • Answer:

    You can also use obje...

Iain McNulty at Quora Visit the source

Was this solution helpful to you?

Other answers

You can use JSON.stringify function. For instance: console.log(JSON.stringify(object)); If you need indentation for better readability (much like PHP's `print_r()`) you can make use of the 3rd argument: console.log(JSON.stringify(object, null, 4));

Eugene Retunsky

console.log(object) should give you what you need: http://cl.ly/4108422d3F1V1d2O3W0K this is the corresponding code: var obj = { first_name:"Bogdan", last_name:"Lazar", sayHello: function(){ alert(this.first_name + ' ' + this.last_name + ' says hello!'); } } console.log(obj);

Bogdan Lazar

If your objective is to inspect the object in order to see what it contains then use console.log(object); this will enable you to view what that object contains. If you want to print the object members as a string then you have no option but to stringify the object. However note that JSON.stringify will only consider the properties of the object and not functions. Alternatively you can write your own function to print the object contents and it should not be very difficult.

Akshar Prabhu Desai

If printing to the console is not doing the job, you can try something like this: function logObject(obj, indentLevel) { indentLevel = +indentLevel || 0; var indent = (new Array(indentLevel + 1)).join(' '); Object.keys(obj).forEach(function (key) { if (obj[key] instanceof Array) { console.log(indent + key, ':', obj[key].join(', ')); } else if (typeof obj[key] === 'object') { logObject(obj[key], indentLevel + 2); } else { console.log(indent + key, ':', obj[key]); } }); } You could swap the console.log() calls for concatenation to a string if for example you wanted to output the object to an element in an HTML document.

Andy Farrell

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.