How can I display a JavaScript object?

2018-12-31 03:25发布

How do I display the content of a JavaScript object in a string format like when we alert a variable?

The same formatted way I want to display an object.

30条回答
爱死公子算了
2楼-- · 2018-12-31 03:51

Use native JSON.stringify method. Works with nested objects and all major browsers support this method.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

Link to Mozilla API Reference and other examples.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

Use a custom JSON.stringify replacer if you encounter this Javascript error

"Uncaught TypeError: Converting circular structure to JSON"
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 03:51

Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}

Print object's content

for (var i in obj){
    console.log(obj[i], i);
}

Console output (Chrome DevTools) :

John 0
Foo 1
Bar 2

Hope that helps!

查看更多
梦寄多情
4楼-- · 2018-12-31 03:52

I think the best solution is to look through the object's Keys, and then through the Object's Values if you really want to see what the object holds...

console.log(Object.keys(obj));
console.log(Object.values(obj));

There is also this new option if you're using ECMAScript 2016 or newer:

Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));
查看更多
浅入江南
5楼-- · 2018-12-31 03:54

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.

查看更多
无与为乐者.
6楼-- · 2018-12-31 03:54

Here's a way to do it:

console.log("%o", obj);
查看更多
情到深处是孤独
7楼-- · 2018-12-31 03:56

I always use console.log("object will be: ", obj, obj1). this way I don't need to do the workaround with stringify with JSON. All the properties of the object will be expanded nicely.

查看更多
登录 后发表回答