7

Given this code, can I alter the behavior of the Stack Overflow snippet editor to make the console.log() behave like Node.js?

var siUnits = [
    { symbol: "m", unit: "meter", quantity: "length"},
    { symbol: "k", unit: "kilogram", quantity: "mass"},
    { symbol: "s", unit: "second", quantity: "time"}
];

console.log(siUnits)

In Node.js the console output is formatted more compactly on just three lines shown below:

[ { symbol: 'm', unit: 'meter', quantity: 'length' },
  { symbol: 'k', unit: 'kilogram', quantity: 'mass' },
  { symbol: 's', unit: 'second', quantity: 'time' } ]

Note: the (as-of-yet unstandardized) console-object working group draft would allow use of a %O "Formats the value as an expandable JavaScript Object". That doesn't work (yet) in stack-snippets.

3
  • Why would you want that? But of course you can include your own inline console in the snippet that does anything you want.
    – Bergi
    Commented Sep 20, 2016 at 17:33
  • The compactness of snippets contributes their value. Commented Sep 20, 2016 at 17:36
  • 4
    For those of you thinking that this is off-topic for Meta...it's talking about Stack Snippets. Slow down.
    – Makoto
    Commented Sep 20, 2016 at 17:40

3 Answers 3

9

You can use JSON.stringify

var siUnits = [
    { symbol: "m", unit: "meter", quantity: "length"},
    { symbol: "k", unit: "kilogram", quantity: "mass"},
    { symbol: "s", unit: "second", quantity: "second"}
];

console.log(JSON.stringify(siUnits))

2
  • Close enough to count as a good answer. I'm not sure why someone downvoted this. Commented Sep 20, 2016 at 17:33
  • 4
    I didn't downvote it, but this is sort of a hackish solution, and in certain cases using stringify will omit important aspects of the object if they were not eligible for serialization.
    – Travis J
    Commented Sep 20, 2016 at 18:08
2

You could probably overload your object's toString function, but to be honest anything done is just going to muddy the example you were trying to make in your question or answer.

Furthermore, the indentation shown is the standard, and changing the current most used style just because it looks slightly different in node doesn't make much sense.

I don't think this is a change that needs to be implemented.

2
0

You can create your own method to accomplish this. JSON.stringify can indent the JSON, but not just for one level. You'd have to compromise.

var siUnits = [
    { symbol: "m", unit: "meter", quantity: "length"},
    { symbol: "k", unit: "kilogram", quantity: "mass"},
    { symbol: "s", unit: "second", quantity: "time"}
];

function stringifyArray(arr) {
    var result = [];
    arr.forEach(function(v) {
        result.push(JSON.stringify(v));
    });
    return "[ "+result.join("\n  ")+" ]";
}

console.log(stringifyArray(siUnits));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .