I totally agree with Emma, but sometimes you may need more control over how the object is represented. In those cases, javascript convert object to string with a custom function can be a great solution. Here’s one way you can format it however you want:
function objectToString(obj) {
return Object.entries(obj)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
}
var o = { a: 1, b: 2 };
console.log('Item: ' + objectToString(o)); // Output: Item: a: 1, b: 2
This approach is super useful when you’re dealing with custom labels or log entries that need a specific format. It’s more flexible than JSON.stringify()
and allows you to define your own style for the string.