0

I'm trying to convert a formatted string to a JavaScript multidimensional array.

I've tried split() and push() functions but neither seem to work. The format should be already right but I can't seem to figure out how to make the string into an array.

Here's the string:

[[24297, 'CWCS Sump 002', -121.50842, 38.54798, '2', 'SEWER SUMP'],[8035, 'CWCS Sump 002A (56)', -121.50842, 38.54798, '2A', 'SEWER SUMP'],[9334, 'CWCS Sump 001', -121.5110297, 38.5703431, '1', 'SEWER SUMP']]

I just want a JavaScript array that is 3x6 (if I counted that right) from that string. The number of rows will vary.

3 Answers 3

1

This is a good candidate for JSON.parse; however, single quotes should be converted to double quotes before it will work. Being careful for escaped quotes, you can try:

const raw = `[[24297, 'CWCS Sump 002', -121.50842, 38.54798, '2', 'SEWER SUMP'],[8035, 'CWCS Sump 002A (56)', -121.50842, 38.54798, '2A', 'SEWER SUMP'],[9334, 'CWCS Sump 001', -121.5110297, 38.5703431, '1', 'SEWER SUMP']]`;

const res = JSON.parse(raw.replace(/(?<!\\)'/g, `"`));
console.log(res);

Sign up to request clarification or add additional context in comments.

3 Comments

I can actually write the string however I want - I had chosen that because I was following a google maps example that had that format.. I am formatting the sting from a database result in traditional asp and returning it through an ajax call
here is the smae string formatted with double quotes on all values: [["24297", "CWCS Sump 002", "-121.50842", "38.54798", "2", "SEWER SUMP"],["8035", "CWCS Sump 002A (56)", "-121.50842", "38.54798", "2A", "SEWER SUMP"]]
I think this is working now once I double quoted the values. Thanks for the help!
1

You can do it with JSON.parse as:

let str = '[[24297, "CWCS Sump 002", -121.50842, 38.54798, "2", "SEWER SUMP"],[8035, "CWCS Sump 002A (56)", -121.50842, 38.54798, "2A", "SEWER SUMP"]]';

let arr = JSON.parse(str);

Notice it better to have the ' around the entire string the " around the string inside. Can do that with:

str.replace("'", """);

1 Comment

the string is being returned by an ajax call to a global variable.
0

According to me It wont be straight forward. You can try like this.

let a = "[
    [24297,'CWCS Sump 002',-121.50842, 38.54798,'2','SEWER SUMP'],
    [8035,'CWCS Sump 002A (56)',-121.50842,38.54798,'2A','SEWER SUMP'],
    [9334,'CWCS Sump 001', -121.5110297,38.5703431,'1','SEWER SUMP']
]";
let c= [];

a.replace('[[','').replace(']]','').split('],[').forEach(
    (x)=>{c.push(x.split(','))}
);
//c is the result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.