Creating a JavaScript array from PHP – square brackets and curly braces - javascript

I am trying to pass code from my PHP backend to the google-chart JavaScript API. I have had success using PHP’s json_encode(), for passing arrays of numbers and strings.
For simple data arrays json_encode() works just fine:
<?php $data = [['Series1', 'Series2'], [0, 1], [2, 3], [3, 4]]; />
<script>
var data = <?php echo(json_encode($data));?>;
</script>
But, the Google Charts API requires that row-parameters be passed as objects in {curly braces}.
Here is the JavaScript array I am trying to produce:
var data = [
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
'Western', 'Literature', { role: 'annotation' } ],
['2010', 10, 24, 20, 32, 18, 5, ''],
['2020', 16, 22, 23, 30, 16, 9, ''],
['2030', 28, 19, 29, 30, 12, 13, '']
];
The trouble is producing the {role: 'annotation'} bit in PHP. Any suggestions?

This should do the trick:
$data = [['Series1', 'Series2', ['role'=>'annotation']], [0, 1], [2, 3], [3, 4]];
You can create objects in php by creating a new stdClass, but an dictionary (key => value array) is converted to JSON the same way (with curly brackets). This would work as well:
$object = new stdClass();
$object->role = 'annotation';
$data = [['Series1', 'Series2', $object], [0, 1], [2, 3], [3, 4]];

You can create an object in PHP and json_encode will create an object from that:
$myObj = new stdClass;
$myObj->role = "annotation";
Then 'json_encode($myObj);' will return the JSON object you want.

Related

Extract data from an array of Object

I have this array of Object that I am getting from my database:
[Array of Object][1]
I would like to make an array of array for each value, but I can't manage to find a way to do it as I'm a beginner of javascript.
For example :
var Stats=[
[39,49,43,42,41,35], //SGW Value for each Object
[37,44,49,46,52,42], //UD Value for each Object
[8,11,8,8,16,15], //Virtual Value for each Object
...
]
The goal is to make a chart on chart.js that look like that :
[Chart Goal][2]
I would need to loop the dataset because I'll add more data and it would be way too long to set each dataset individually.
Thanks for your time.
You can do it like this:
let array1 = [
{
param1: 10,
param2: 20
},
{
param1: 30,
param2: 40
}
]
let array2 = array1.map(item => Object.values(item));
console.log(array2); // prints [[10, 20], [30, 40]]
First of all you need to create an array for each property you want to plot; i.e.:
var fsp = [],
msg = [],
sgw = [];
Then you can loop over your dataset and put the data in each array:
yourArray.forEach(function(obj){
//obj takes the value of each object in the database
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
})
or, if you are more familiar with for loop
for(var obj of yourArray){
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
}
Finally you can create an array as you pointed in your example
var result = [];
result.push(fsp, msg, sgw);
And the result will be
[
[89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
[77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
[24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
]
For more informations take a look at Array.forEach(), Array.push() and for...of documentations
EDIT
As you pointed in your comment, you can generate arrays dynamically creating an object like var arrays = {};. Then in forEach(), or if for...of, you need to loop over objects with a for...in loop. The variable you declare in loop's head takes the value of index, numeric for Arrays, literal for Objects. You have to do something like:
yourArray.forEach(function(obj){
for(let index in obj){
if(!arrays[index]) // check if property has already been set and initialized
arrays[index] = []; // if not, it's initialized
arrays[index].push(obj[index]) // push the value into the array
}
})
Note that Object has been treated as Array because you access its properties with a variable filled at runtime.
The result will be:
arrays = {
fsp: [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
msg: [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
sgw: [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
}
To obtain only arrays use Object.values().
If you cannot imagine how this works, I suggest you to make some examples in Chrome Developer Tools' console, or in Node's console, or wherever you can have a realtime feedback, putting in the middle of code some console.log() of variables

LoDash: How to remove null values and index of null values from two arrays with _.flow?

Problem
I have an array of arrays:
const multiple = [[1, 2, null, 7], [6, 8, 9, 1]]
Now I'd like to remove all null values and the corresponding element from the other array which results in:
[[1, 2, 7], [6, 8, 1]]
I'm able to do that but I'm looking for a solution with _.flow.
Approach
This is my approach that doesn't return an array of arrays and also doesn't remove the element from the other array.
_.flow([
xorWith(_.isNull)
])([1, 2, null, 7], [6, 8, 9, 1])
1. Update
My input will always be [[ // Elements], [ // Elements]]. It wasn't clear at my approach.
const multiple = [[1, 2, null, 7], [6, 8, 9, 1]];
const withoutNulls = (arr) => _.every(arr, _.negate(_.isNull));
const result = _.flow(
_.zip,
(tuples) => _.filter(tuples, withoutNulls),
_.unzip
)(...multiple)
console.log(result);
<script src="https://unpkg.com/lodash#4.17.5/lodash.js"></script>
Does that suit your needs, or you want it exactly with your functions set?
I can't get the basic idea of yours, because the flow function accepts functions and call them in chain, but it is not as in your case.
_.flow((...args) => _.map(args, arr => _.filter(arr, v => !_.isNull(v))), console.log)([1, 2, null, 7], [6, 8, 9, 1])
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.5/lodash.min.js"></script>

Using context variables as javascript parameters

I'm working on a project in Django, for part of it I'm trying to use Googles chart api, which uses a Javascript function to plot the graph. So what I'm trying to do is generate the graph data in my views.py and then pass the data through the context variables to the script. To test this I tried to do:
graphplot = [['Age', 'Weight'],[ 8, 12],[ 4, 5.5],[ 11, 14],[ 4, 5],[ 3, 3.5],[ 6.5, 7]]
context = {
"graphplot": graphplot,
}
in my views.py then I have:
var data = google.visualization.arrayToDataTable({{graphplot}});
in my template, however this doesn't seem to work.
When I do:
var data = google.visualization.arrayToDataTable([
['Age', 'Weight'],
[ 8, 12],
[ 4, 5.5],
[ 11, 14],
[ 4, 5],
[ 3, 3.5],
[ 6.5, 7]
]);
It does show the graph so I know it's not a problem with the JavaScript.
Any help would be appreciated
Try this, It should work.
var plot_data = {{graphplot}};
var data = google.visualization.arrayToDataTable(plot_data);

data parsing using a csv file in d3

consider the example shown in the link Labeling the axis with alphanumeric characters. Is this the correct way to parse var data?
var data = []
d3.csv("data.csv", function(data) {
data = data.forEach(function(d) { return [ x[d[0]], y[d[1]]] });
console.log(data)
});
data.csv should hold these values
[2, 2],
[3, 3],
[4, 4],
[5, 4],
[5.5, 5],
[6, 6],
[6, 7],
[6.5, 8],
[6.5, 16],
[17, 16]
Assuming that you meant that data should hold those values, your data.csv should look like the following:
first,second
2,2
3,3
4,4
5,4
5.5,5
6,6
6,7
6.5,8
6.5,16
17,16
And then you can parse it using the names of the fields:
var data = []
d3.csv("data.csv", function(csvData) {
// By default, all the values read are treated as strings.
// So have to make them numbers explicitly
data = csvData.forEach(function(d) { return [ +d.first, +d.second ] });
console.log(data);
// Draw the chart here.
});

Javascript get value from array error

I need some help! Im retrieving some values from mySQL database using an external 'grabber'.
<?php
$datapiechart = file_get_contents("url which retrieves the values from MySQL");
?>
Which results in:
[{ "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }]
Then I want to select the values in this array.
<SCRIPT>
dataObjectdatapiechart = <?php echo $datapiechart; ?>
</SCRIPT>
<script> dataObjectdatapiechart.Name1</script>
I don't get whats going wrong here.
dataObjectdatapiechart is an array (with only one element), so you need to access it's contents using an indexer:
var item = dataObjectdatapiechart[0]; // Retrieve the object from the array
var name1 = item.Name1;
var name2 = item.Name2;
var name3 = item.Name3;
//etc.
Use
dataObjectdatapiechart[0].Name1
The Object { "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }
is at 0th position of the array.

Categories