简体   繁体   English

在js结构中转换数据

[英]convert data in js structure

I am getting data from php like:我从 php 获取数据,例如:

[{'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:但在 js 中我想这样转换:

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不,它不是从 controller 得到的 ajax 响应,就像 var values = "{{myValue}}" 这样我得到了

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:在这种情况下,如果您删除包装引号就可以了 - JavaScript 可以在 object 文字中使用单引号属性名称:

var values = {{myValue}};

What the JavaScript engine will see is: JavaScript 引擎将看到的是:

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).如果它是 ajax 响应,您最好的办法是修复 PHP,使其提供有效的 JSON(双引号而不是单引号)。 Then you could just parse the result with JSON.parse .然后你可以用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.改为修复 PHP 侧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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