简体   繁体   中英

Javascript string to multidimensional array of numbers

Ive been reading semilar questions and answers trying to get a solution to this, im working on maps and getting strings that I have to convert to arrays... I got an string that's given to me as variable that I have access on it as string:

coords = '[42.46329472141537,21.46498522471254],[42.463191829327116,21.4654574564449],[42.463524249310545,21.465586246917347],[42.463642970305486,21.465092550106277]';

I need this variable to be an array, I tried JSON.parse it's throwing me an error, I tried to map(Number) that's not defined and Ive tried to split, it's deforming my array... As result I need the array to be in this format:

var newCoords = Array(Array([42.46329472141537,21.46498522471254]),Array([42.463191829327116,21.4654574564449]),Array([42.463524249310545,21.465586246917347]),Array([42.463642970305486,21.465092550106277]));

Every advice will be helpful.

To make it parsable you have to wrap the arrays in a parsable object (object property, another array and so on);

To wrap your string in another object you can take advantage of template literals :

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

 // Wrap arrays in another array to get a parsable object const coords = '[42.46329472141537,21.46498522471254],[42.463191829327116,21.4654574564449],[42.463524249310545,21.465586246917347],[42.463642970305486,21.465092550106277]'; console.log(JSON.parse(`[${coords}]`));

You can use split function to make an array:

 let coords = '[42.46329472141537,21.46498522471254],[42.463191829327116,21.4654574564449],[42.463524249310545,21.465586246917347],[42.463642970305486,21.465092550106277]'; let array = coords.split('],[').map( c=> c.replace(/\[/g, '').replace(/]/g, '').split(',')); console.log(array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM