Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array containing a Symbol to string?

I have an array that could contain Symbol() item. Array.toSring brings an exception.

const s = [10, 'abc', Symbol('test')].toString(); // this throws an exception
console.log([10, 'abc', Symbol('test')]); // this works

What is the best way to convert such array to a string (like console.log does)?

like image 654
bladerunner2020 Avatar asked Oct 01 '19 09:10

bladerunner2020


1 Answers

.map the array, calling toString on each symbol first:

const s = [10, 'abc', Symbol('test')]
  .map(val => typeof val === 'symbol' ? val.toString() : val)
  .join(',');
console.log(s);

To turn a Symbol into a string, you have to do so explicitly.

Calling toString on a symbol is permitted, because that invokes Symbol.prototype.toString().

In contrast, trying to turn the Symbol into a string implicitly, like with Array.prototype.join, (or Array.prototype.toString, which internally calls Array.prototype.join, or +, etc), invokes the ToString operation, which throws when the argument is a Symbol.

like image 128
CertainPerformance Avatar answered Oct 03 '22 21:10

CertainPerformance