Search code examples
javascriptlaravel-5multidimensional-arrayjavascript-objects

Dynamically create a multidimensional javascript object


Please I have been struggling to create a javascript multidimensional object dynamically from several sources including a PHP array of 3 months and other variables as follows:

I have written the read some tutorials and written the following code and still getting errors:

 <script type='text/javascript'>
 var chart_data={};
 </script>



 @foreach($chart_data as $mth => $data)
        <script type="text/javascript">
            chart_data={'months':{"{{$month}}":"data":{!!json_encode($data['data'])!!}}};
            chart_data={'months':{"{{$month}}":'ykeys':{!!json_encode($data['ykeys'])!!}}};
            chart_data={'months':{"{{$month}}":'labels':{!!json_encode($data['labels'])!!}}};
            var chart_bar_colors={!!json_encode($chart_bar_colors)!!};
        </script>
        @endforeach

I keep getting the following error in the console:

Uncaught SyntaxError: Unexpected token :

I also see the following error on examining the source from developer tools: The error from source in Chrome developer tools

I am trying to build a js data structure as follows:

chart_data['months']['Oct']['data']['some data here']
chart_data['months']['Oct']['ykeys']['some data here']
chart_data['months']['Oct']['labels']['some data here']
chart_data['months']['Nov']['data']['some data here']
chart_data['months']['Nov']['ykeys']['some data here']
chart_data['months']['Nov']['labels']['some data here']
chart_data['months']['Dec']['data']['some data here']
chart_data['months']['Dec']['ykeys']['some data here']
chart_data['months']['Dec']['labels']['some data here']

Please I would appreciate any guide to resolve this Thank you all


Solution

  • <script type='text/javascript'>
        var chart_data={
            'month' : {},
        };
    
        @foreach($chart_data as $mth => $data)
    
        chart_data.month['{{ $mth }}'] = {
            'data' : {!!json_encode($data['data'])!!} ,
            'ykeys' : {!!json_encode($data['ykeys'])!!} ,
            'labels' : {!!json_encode($data['labels'])!!} ,
        }
    
        @endforeach
    </script>