let str="{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result=[{"SPOT":0,"0":10,"1":0},{"SPOT":1,"0":5,"1":5}];
How to convert string to array of object
let str="{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result=[{"SPOT":0,"0":10,"1":0},{"SPOT":1,"0":5,"1":5}];
How to convert string to array of object
Well this is not the best approach I would say but still, it will solve your problem:
let str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let newStr = str.replace("},{", "}TempString{"); //append any dummy string in the existing one
let result = newStr.split("TempString");
console.log(result)
We can make it look like an array using template literals and a little bit of replace.
When it looks right we can use JSON.parse to actually turn it into an array
Now we have an array we can use forEach to go through each string and make them look like objects, we'll use replace again.
Once we've made each string look like an object we can push them into an empty results array, we'll have to make one outside of the loop.
Putting all this together looks a little like this:
const str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}";
let result = [];
JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => {
result.push(JSON.parse(e.replace(/{/g, `{"`).replace(/:/g, `":`).replace(/,/g, `,"`)));
});
console.log(result)
I hope you find this helpful.