user10913420
user10913420

Reputation:

Preserve Nested Array Structure When Converting to String, JavaScript

When I create a nested array, say:

let x = [[0, 1], 2, [3, [4, 5]]]; 

and convert it to a string with .toString():

x.toString();
-> "0,1,2,3,4,5"

It doesn't preserve the nested structure of the array. I would like to get something like:

x.toString();
-> "[0,1],2,[3,[4,5]]"

Is there any smarter way of doing this other than looping through elements of x, testing if an element is an array etc.?

Upvotes: 2

Views: 529

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use JSON.stringify and replace

 ^\[|\]$

enter image description here

let x = [[0, 1], 2, [3, [4, 5]]]; 

let final = JSON.stringify(x)

// with regex
console.log(final.replace(/^\[|\]$/g,''))

// without regex
console.log(final.slice(1, -1))

Upvotes: 3

Jonas Wilms
Jonas Wilms

Reputation: 138257

Or possibly use a generator to build up a string manually:

 function* asNested(array) {
    for(const el of array)
      if(Array.isArray(el)) {
         yield "[";
         yield* asNested(el);
          yield "]";
      } else yield el.toString();
 }

 const result = [...asNested([[1, 2], [3, 4]])].join("");

Upvotes: 1

Related Questions