Home > database >  How do I turn a string into not being a string?
How do I turn a string into not being a string?

Time:07-25

If I have an array in js:

['{lat:52.5159, lng:13.3777}', '{lat:37.773972, lng:-122.431297}', '{lat:39.916668, lng:116.383331}']

How would I make the values not be strings. For example, they should look like this:

[{lat:52.5159, lng:13.3777}, {lat:37.773972, lng:-122.431297}, {lat:39.916668, lng:116.383331}]

Is this possible? If so, how can I do this?

CodePudding user response:

Because those aren't JSON strings you can't parse them.

Use a regex to find the numbers, and then map over the array. On each iteration match the numbers, and then return the object making sure you coerce the strings to numbers.

const arr = [
  '{lat:52.5159, lng:13.3777}',
  '{lat:37.773972, lng:-122.431297}',
  '{lat:39.916668, lng:116.383331}'
];

const re = /-?[\d] \.[\d] /g;

const out = arr.map(str => {
  const [ lat, lng ] = str.match(re);
  return { lat:  lat, lng:  lng };
});

console.log(out);

CodePudding user response:

So it looks like you want to parse the strings in your array to Objects. For the strings in your post, they won't be easily converted to an object because they aren't proper JSON. If the initial array is formatted like this instead:

['{"lat":52.5159, "lng":13.3777}', '{"lat":37.773972, "lng":-122.431297}', '{"lat":39.916668, "lng":116.383331}']

From here we can simply do an array map to get it to Objects from Strings:

var input = ['{"lat":52.5159, "lng":13.3777}', '{"lat":37.773972, "lng":-122.431297}', '{"lat":39.916668, "lng":116.383331}']

input = input.map(value => JSON.parse(value));

This will make input look like this:

[{lat:52.5159, lng:13.3777}, {lat:37.773972, lng:-122.431297}, {lat:39.916668, lng:116.383331}]
  • Related