0
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

Manikandan
  • 51
  • 1
  • 11
  • Using [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to return an array of 'object string'. Then, using [JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) to parse each object string to object. – Lam Pham May 15 '18 at 10:20

2 Answers2

0

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)
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
Harsh Jaswal
  • 447
  • 3
  • 14
0

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.

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33