How to convert array containing a Symbol to string?

Viewed 356

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)?

3 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.

simply you can convert the symbol to string instead of converting the whole array

const s = [10, 'abc', Symbol('test').toString];

Can you do a small operation on the array before .toString() is called on the array. Something like this:

function myFunction() {
  var fruits = [10, 'abc', Symbol('test')];
  var test = [];
  for(item of fruits){
      if(typeof(item) === "symbol"){
          test.push(item.toString());
      }
      else{test.push(item)}

  }
  var x = test.toString();

The thing is we don't want to call .toString() method on each item of the array.

Related