简体   繁体   中英

convert data in js structure

I am getting data from php like:

[{'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 31.5755, 'lng': -85.279}, {'lat': 32.2334, 'lng': -86.2085}, {'lat': 32.2334, 'lng': -86.2085}, {'lat': 42.8142, 'lng': -73.9396}, {'lat': 42.8142, 'lng': -73.9396}, {'lat': 42.8142, 'lng': -73.9396`enter code here`}, {'lat': 42.8142, 'lng': -73.9396}, {'lat': 42.8142, 'lng': -73.9396}, {'lat': 38.6207, 'lng': -83.8067}, {'lat': 42.3644, 'lng': -71.0633}, {'lat': 40.0625, 'lng': -79.8953}, {'lat': 34.4197, 'lng': -119.7078}, {'lat': 42.8142, 'lng': -73.9396}, {'lat': 42.0702, 'lng': -72.6227}]

but in js i want to convert this like:

const locations = [
  { lat: -31.56391, lng: 147.154312 },
  { lat: -33.718234, lng: 150.363181 },
  { lat: -33.727111, lng: 150.371124 },
  { lat: -33.848588, lng: 151.209834 },
  { lat: -33.851702, lng: 151.216968 },
  { lat: -34.671264, lng: 150.863657 },
  { lat: -35.304724, lng: 148.662905 },

];

can anyone please suggest me how can i convert this in this way. i want to remove the single quotes and want new array of result like this

no its not the ajax response getting from the controller like var values = "{{myValue}}" in this way i am getting

In that case, it's fine as-is if you remove the wrapper quotes — JavaScript is fine with single-quoted property names in object literals:

var values = {{myValue}};

What the JavaScript engine will see is:

var values = [{'lat': 31.5755, 'lng': -85.279}, /*...*/];

which is fine.


If it were an ajax response, your best bet would be to fix the PHP so it provides valid JSON (double quotes rather than single quotes). Then you could just parse the result with JSON.parse .

As a second-best solution, if you can't do that, since the only single quotes in the data are the ones around the property names, you could replace them with double quotes and then parse the result:

const locations = JSON.parse(theDataString.replace(/'/g, '"'));

But , that only works because there aren't any other single quotes. It's not a good approach; fix the PHP side instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM