Laravel和Javascript中的对象到数组转换



我的项目有问题。我希望我的数据将以这种格式返回

var locations = [
['Bondi Beach', 23.779328, 90.333686, 4],
['Coogee Beach', 23.815266, 90.359724, 5],
['Cronulla Beach', 23.824754, 90.414227, 3],
['Manly Beach', 23.804163, 90.456153, 2],
['Maroubra Beach', 23.764990, 90.450636, 1]
];

这是我的控制器

public function map() {
Auth::user()->hasAccess([1, 8, 9]);
$sites = Site::orderBy('created_at', 'DESC')->select('siteId', 'latitude', 'longitude')->get();
return view('sites.map', compact('sites'));
}

我的Javascript代码是

var locations = {!! json_encode($sites) !!};

但它返回

var locations = [
{"siteId":"GPBNP1","latitude":"24.01144","longitude":"90.18492"},
{"siteId":"BHHZH1","latitude":"23.60953","longitude":"90.90608"}
];

以这种格式。我没有找到任何解决方案。任何反馈都将是可观的

您可以这样更改格式:

var locations = [
{"siteId":"GPBNP1","latitude":"24.01144","longitude":"90.18492"},
{"siteId":"BHHZH1","latitude":"23.60953","longitude":"90.90608"}
];
var result = locations.map((location, i) => [location.siteId, location.latitude, location.longitude, i]);
console.log(result)

例如,如果您需要位置名称,则必须更改获取请求。

如果你想以一种更大的方式做到这一点,你可以使用toArray()

public function map() {
Auth::user()->hasAccess([1, 8, 9]);
$sites = Site::orderBy('created_at', 'DESC')->select('siteId', 'latitude', 'longitude')->get()->toArray();
return view('sites.map', compact('sites'));
}

相关内容

  • 没有找到相关文章

最新更新