How can I display a JavaScript object?

2.2k2009 年提問 · maxjackie ·javascriptserializationjavascript-objects 主題:物件、JSON 與拷貝 → 在 Stack Overflow 看原文 ↗

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.

重點答案

1.4k採納 by Kenan Banks 原文 ↗

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);

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"
展開這則答案

Simple display

Assembles direct properties and their values. Does not include objects within objects.

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
console.log(output);

Hierarchical display

A more full example includes objects within objects. The logic is a little tricky as some versions of Javascript detect arrays and null as objects. This code also displays functions in most browsers.

const order = {Apple: 12, Banana: 4, Watermelon: 1, Orange:8, Grape: {Muscat: 20}, Summary: [12,4,1,8,20], Pack: false, Null: null};

function objectAsString(obj) {
  var output = '';
  for (var property in obj) {
    if(obj.hasOwnProperty(property) && typeof obj[property] !== 'function') {
      var value = obj[property];
      if(typeof value === 'object' && !Array.isArray(value) && value !== null) {
        value = '{' + objectAsString(value) + '}';
      }
      output += property + ': ' + value +'; ';
    }
  }
  return output;
}
console.log(objectAsString(order));

Hierarchical display for post-2015 browsers

const order = {Apple: 12, Banana: 4, Watermelon: 1, Orange:8, Grape: {Muscat: 20}, Summary: [12,4,1,8,20], Pack: false, Null: null};

function objectAsString(obj) {
  return Object.keys(obj)
    .map(property => {
      const value = obj[property];
      if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
        return `${property}: {${objectAsString(value)}}`;
      } else {
        return `${property}: ${value}`;
      }
    })
    .join('; ');
}

console.log(objectAsString(order));
//  Apple: 12; Banana: 4; Watermelon: 1; Orange: 8; Grape: {Muscat: 20; }; Summary: 12,4,1,8,20; Pack: false; Null: null; 

If you want to omit functions, you would insert this line before '.map':

.filter(property => typeof obj[property] !== 'function')