Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

Javascript works but need to change string to array

I had this question after viewing Anyway to format this array data differently?.

The solution in my question above works. You can see it in this JSFiddle that  Huseyin create here https://jsfiddle.net/5t10qr3c/

You see the string output is like this: {"name": "county1", "data": [144, 333]}{"name": "county2", "data ": [123, 2302]}

I actually need this in an array like this: For example array of 2
[Object, Object]
0: Object
    data: Array(2)
              0: 144
              1:333
     name: "county1"
1: Object
   data: Array(2)
             0: 123
             1: 2302
   name: "county2"

I tried these
I used "split" but that won't work

I thought just wrapping the "str" with [] would do it but no, it's still a  string.

I'm thinking as the string is being build, I need to push it into an array? but not sure.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Do you mean like this
<script>
var str = '{"name": "county1", "data": [144, 333]}{"name": "county2", "data ": [123, 2302]}';
str = '[' + str.replace(/\}\{/,'},{') + ']';
var obj = JSON.parse(str);
console.log(obj)
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Camillia

ASKER

let me try it now.( I've been at this for 3 hours now and found a C# example and was about to redo the code). I'll post back.
If you are building it why not just put the opening '[' at the start, closing ']' at the end and a ',' between each object? then you can just run JSON.parse() on the string.

I didn't know this. I'll try this first.
I can't believe it...it worked! thank you so much, as always. You're a life saver.
As always you are most welcome.