1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

console.log()でObjectの値をみやすくする

Posted at

Objectの階層が深くなると以下の[Object]のように全てのプロパティが表示されない。

 console.log({_id: 11111, data: {1111111:22222222}}, 'bbbbb', {a:123, b:'bbb', cdata:{_id:'c', data: {1:1,2:2}, 1:{2:{3:{4:{5:5}}}}}})

==>

{ _id: 11111, data: { '1111111': 22222222 } } 'bbbbb' { a: 123,
  b: 'bbb',
  cdata: { '1': { '2': [Object] }, _id: 'c', data: { '1': 1, '2': 2 } } }

JSON.stringifyのオプション使ってコンソール出力すれば上記は解決できるけど、debugでよく使うのでついでにcolorsも使ってこんな感じの処理書いて使い回せばそれなりに便利

sample.js

var colors = require('colors');
var stringify = JSON.stringify;

function print(_c, args) {
    for (var i = 0, l = args.length; i < l; i++) {
        var arg = args[i];

        var val = (typeof arg === 'object') ? stringify(arg, null, '\t') : arg;
        console.log(String(val)[_c]);
    }
}

var _colors = ['green', 'red', 'black', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'grey']
for (var i = 0, l = _colors.length; i < l; i++) {
    var c = _colors[i];

    (function(_c){
        exports[_c] = function() {
            print(_c, arguments);
        }
    }(c))
}

// alias
exports.log = exports.green;

使い方

hoge.js
var c = require('./sample');
c.log({_id: 11111, data: {1111111:22222222}}, 'bbbbb', {a:123, b:'bbb', cdata:{_id:'c', data: {1:1,2:2}, 1:{2:{3:{4:{5:5}}}}}})

==>
{
    "_id": 11111,
    "data": {
        "1111111": 22222222
    }
}
bbbbb
{
    "a": 123,
    "b": "bbb",
    "cdata": {
        "1": {
            "2": {
                "3": {
                    "4": {
                        "5": 5
                    }
                }
            }
        },
        "_id": "c",
        "data": {
            "1": 1,
            "2": 2
        }
    }
}

c.log(), c.green(), c.red(),,,とか。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?