-1

i have the below array:

let arr= ["5,5", "Orange", "6,1"];

Every item in that arr is random string and contains any character (",",";",...")

For some reasons, i have to convert arr to string.

I used let s = arr.toString() and got the string: s= "5,5,Orange,6,1"

The problem is: I have to convert that string back to the array without reusing arr and losing the format. If i use string.split(","), the result is ["5", "5", "Orange", "6", "1"] instead of ["5,5", "Orange", "6,1"]

i know toString() is the same to join array with ",", but if i use arr.join() with other character then split(), it seems silly because item in arr is random and can contain any character.

Thanks a lot!

Quang Thái
  • 649
  • 5
  • 17
  • Encode it as JSON then … – CBroe Jun 23 '20 at 09:13
  • 5
    That's what JSON is for: instead of converting the array to a plain string, which can cause issues due to ambiguous use of the `,` separator in the array items, use `JSON.stringify` to convert your array to JSON and then you can always parse it back to an array using `JSON.parse` – Terry Jun 23 '20 at 09:13
  • Does this answer your question? [Convert JS object to JSON string](https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – user120242 Jun 23 '20 at 09:14
  • Does this answer your question? [Convert array to JSON](https://stackoverflow.com/questions/2295496/convert-array-to-json) – VLAZ Jun 23 '20 at 09:17

1 Answers1

2

This is what JSon is for.

let arr= ["5,5", "Orange", "6,1"];

let arrStr = JSON.stringify(arr);

console.log('arrStr: ', arrStr, 'as string');

let newArr = JSON.parse(arrStr);

console.log('newArr:', newArr);
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30