Node.js - console.log does not show items in array but instead shows [Object]

后端 未结 4 1495
死守一世寂寞
死守一世寂寞 2020-12-11 23:41

I have a problem with logging out the contents of an array inside an object. The actual object looks like this

   var stuff = { accepted: [ \'item1\', \'ite         


        
相关标签:
4条回答
  • 2020-12-12 00:13

    This is the default way for some browser and implementations of showing too complex or deep objects/arrays with console.log. An alternative is to use JSON.stringify with console.log:

    var stuff = {
      accepted: ['item1', 'item2'],
      rejected: [],
      response: 'Foo',
      envelope: {
        from: 'The sender',
        to: ['new item1', 'new item2']
      },
      messageId: 'xxxxxxxxxxxxx'
    }
    
    
    console.log(JSON.stringify(stuff, null, 4));

    EDIT:

    Another alternative is to use console.dir in case you have a too complex or recursive object, see https://stackoverflow.com/a/27534731/6051261

    0 讨论(0)
  • 2020-12-12 00:13

    It looks like this is an old topic, anyway

    I've faced the same issue, embedded array printed as [Array].

    It is because of console.log in the node.js uses util.inspect for print, the default depth is 2. So, to print something which is deeper than 2 followings can be used:

    const util = require('util')
    console.log(util.inspect(errors, true, 10))
    
    0 讨论(0)
  • 2020-12-12 00:14

    Try it with: console.log(JSON.stringify(variable))

    0 讨论(0)
  • 2020-12-12 00:27

    If you like Chrome devtools, that folds your json objects and let you observe a lot of things, you can use the --inspect flag:

    node --inspect index.js
    

    The console will then give you an URL and you just have to copy paste in Google Chrome to enjoy Google Chrome console.

    More information on this link

    0 讨论(0)
提交回复
热议问题