When I do:
const obj = [{
test1: 'data',
test2: 'data',
test3: 'data',
}];
console.log(obj);
The object will be displayed in JSON-like syntax in the console:
[ { test1: 'data',
test2: 'data',
test3: 'data' } ]
But when I do:
const obj = [{
test1: 'data',
test2: 'data',
test3: 'data',
}];
console.log(`JSON Data\n\n${obj}`);
it will be displayed as “[object Object]”. So instead I do:
const obj = [{
test1: 'data',
test2: 'data',
test3: 'data',
}];
console.log(`JSON Data\n\n${JSON.stringify(obj)}`);
which displays it as a string:
JSON Data
[{"test1":"data","test2":"data","test3":"data"}]
I want to do a console.log
of the object followed by some text in a template literal whilst keeping the syntax it had when printed stand-alone, like so:
JSON Data
[ { test1: 'data',
test2: 'data',
test3: 'data' } ]
How can I do it?
When you use a template literal, the result is a string. If you want to add texts labels before/after the logged data, or other values, separate them by comma:
var data = { a: 1, b: [1, 2] };
console.log('Before:', data, '\n\nJSON Data Displayed Above');
console.log(data, '\n\nAfter');
console.log('Before\n', data, '\n\nAfter');