Ron
Ron

Reputation: 57

Array to string conversion not working

I am trying to print out this code in a string.

var x = [[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]];`
console.log(x.toString());

This is what shows up.

String Array

When I print out the regular string, like so-

console.log(x);

This is what shows up-

Array

Is there any way I can print out a string with the square brackets? I want the result to be something like "[[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]]".

I need to add this value to a eval function, which is why I need to add the entire array (as a string with the brackets) to the function.

Is there any way this can be possible (preferably without additional libraries)?

Upvotes: 1

Views: 3139

Answers (4)

Satyapriya Mishra
Satyapriya Mishra

Reputation: 130

The best way is to use the json.stringify() method.The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified. MAy the below url help you where you can get complete reference.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can use Array#map with string concatenation.

'[' + x.map(e => '[' + e + ']') + ']'

var x = [
  [1, 2, 3, 4.5, 6],
  [7, 8.5, 9.5, 10]
];

var string = '[' + x.map(e => '[' + e + ']') + ']';
console.log(string);
document.body.innerHTML = string;

If the elements of the main array are not always array, Array.isArray can be used with ternary operator.

'[' + x.map(e => Array.isArray(e) ? '[' + e + ']' : e) + ']'

var x = [
    [1, 2, 3, 4.5, 6],
    [7, 8.5, 9.5, 10],
    'name',
    10
];

var string = '[' + x.map(e => Array.isArray(e) ? '[' + e + ']' : e) + ']';
console.log(string);
document.body.innerHTML = string;

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239473

Use JSON.stringify to convert the Array to a JSON Array.

var x = [[1, 2, 3, 4.5, 6], [7, 8.5, 9.5, 10]];
console.log(JSON.stringify(x));
// [[1,2,3,4.5,6],[7,8.5,9.5,10]]

Upvotes: 3

Soroush Mehraein
Soroush Mehraein

Reputation: 21

You can use JSON.stringify() to serialize x into a string.

console.log(JSON.stringify(x)) will return what you're looking for.

 console.log(JSON.stringify(x))
 [[1,2,3,4.5,6],[7,8.5,9.5,10]]

Upvotes: 2

Related Questions