JL Peyret
JL Peyret

Reputation: 12184

console.dir - how to show what object it applies to / label it?

Given a declaration like

myobj = {a:1, b:2};

I can write console.dir(myobj). This results in

{ a: 1, b: 2 }

But say I want to remind myself, in a complex debugging session, what the console.dir is about:

I can write

console.log("myobj"); console.dir(myobj);

This will print

myobj
{ a: 1, b: 2 }

But it's a bit clunky.

Using console.log("myobj:" + myobj);

prints out

myobj:[object Object]

which doesn't work at all. Is there a better way to label a console.dir?

Upvotes: 1

Views: 1161

Answers (3)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

If using Node.js, you can print the label without a trailing newline by using process.stdout.write:

function inspect(label, data) {
  process.stdout.write(`${label}: `)
  console.dir(data, { depth: null })
}

{ depth: null } is kind of irrelevant here, but it's also the reason why I use console.dir in Node.js; it allows logging objects without deeply nested sub-objects being abbreviated as [Object] and arrays being abbreviated as [Array].

Example:

const myobj = {
  foo: {
    bar: {
      baz: {
        qux: true,
        ham: 'spam',
      },
      items: [1, 2, 3],
    },
  },
}

console.log('my object:', myobj)
//=> my object: { foo: { bar: { baz: [Object], items: [Array] } } }

inspect('my object', myobj)
//=> my object: {
//     foo: { bar: { baz: { qux: true, ham: 'spam' }, items: [ 1, 2, 3 ] } }
//   }

Upvotes: 0

Chase
Chase

Reputation: 3126

You could just wrap your named variable in an object and the name will then be visible as the first layer of expansion.

myobj = {a:1, b:2};

console.dir({myobj});


You can also use "groups" if you want the top-level wrapper to be your variable's name. Probably you'd want to do this with some sort of helper (and I don't really even suggest it, but it may meet your needs so just showing it as a demonstration):

function labeledConsoleDirGroup(wrappedVar) {
  const varName = Object.keys({myobj})[0];
  console.group(varName);
  console.dir(wrappedVar[varName]);
  console.groupEnd(varName);
}

// Later ...
const myobj = {a: 1, b: 2};
labeledConsoleDirGroup({myobj});

Note that this doesn't work in the in-built code snippet runner since it doesn't support groups. But it looks like this in Chrome:

looks like this in Chrome

Upvotes: 4

javascwipt
javascwipt

Reputation: 1178

dir and log take multiple arguments, you are getting that last output because you can't concatenate a string to an object, here is a proper way:

console.log("myobj:", myobj);

Use a comma and just pass multiple arguments instead.

Upvotes: 0

Related Questions