Highcharts and JSON - json

Let me know how to declare multiple data in Y because my script doesn't work.
My JSON file is:
[{"metier":"Administratif","annee2005":182373,"annee2006":188153,"annee2007":194636},
{"metier":"Igenieur","annee2005":9140,"annee2006":9483,"annee2007":4321},
{"metier":"Chef de chantier","annee2005":25118,"annee2006":29417,"annee2007":32081},
{"metier":"Commercial","annee2005":13122,"annee2006":16294,"annee2007":17706}]
My Javascript is
$.getJSON('dataTest.json', function(data) {
var output = [];
$.each(data,function(i,d){
output.push(
{
name: d.metier,
y: [d.annee2005,d.annee2006]
}
);
});
$('#container').highcharts({
chart:{
type:'column'
},
xAxis:{
type:'category'
},
series: [{
name: 'Métiers',
data: output
}
]
});
});

In output.y you have array of two values but it must be one value for y, you need create 2 series for output 2 graphics

Related

HighCharts Angular - data from API not showing in chart

I am trying to show the data from the bgpie API in my chart.
The data property of the chart accepts this format:
chartOptions: Options = {
...
series: [{
...
data: [[1, 5], [2, 3], [3, 8]];
...
}]
The format is an array of couples with the first value of the couple being the x-axis value and the second being the y-axis value. My API has a different format: [{item1,item2}, {item1,item2}, {item1,item2}].
In order to change it to [[item1,item2], [item1,item2], [item1,item2]] I've done this:
chartDataX: number[] = [];
chartDataY: number[] = [];
chartData: any[] = [];
ngOnInit(): void {
this.chartService.getMostFrequentUpdateData().subscribe(
(data: ChartData[]) => {
for (let i = 0; i < data.length; i++){
this.chartDataX.push(data[i].item1);
this.chartDataY.push(data[i].item2);
this.chartData.push([this.chartDataX[i], this.chartDataY[i]]);
}
});
this.chartOptions.series = [
{
name: 'ao',
type: 'line',
data: this.chartData,
color: '#009879',
}
];
}
With getMostFrequentUpdateData() being a function that makes the http call to the API:
getMostFrequentUpdateData(): Observable<ChartData[]>{
return this.http.get<ChartData[]>('https://bgpie.net/api/rrc/00/mostfrequentstatefrequencycdf');
}
This is a public repository containing the project (There might be some merge conflicts).
The susbcribe is async so your this.chartData is empty when you are assigning it to the chart object.
You can refactor as below with some suggestions to improve the code as well:
this.chartService.getMostFrequentUpdateData().subscribe(
(data: ChartData[]) => {
this.chartOptions.series = [
{
name: 'ao',
type: 'line',
data: data.map(e => [e.item1, e.item2]),
color: '#009879',
}
];
});

How to get values from json object array and add to another array in angular

I have Following json object :
var arr =[{
0:M: "LED"
id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2"
}, {
1:M: "LED"
id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2"
}]
Now it has two values,but it can have multiple value because it is fetch from database.
From this json i wnat to pick values with key upin,mtype,land and add to another array.
I have tried following
for(let item of data){
// this.console.log(item)
this.upins = item.upin;
this.console.log(this.upins);
}
this.console.log(this.upins);```
It shows last index value
I want result as follows
var arr = [{
upins: abc,
mtyp:xyz,
land:123
},{
upins:123,
mtype:pqr,
land:555
}]
Assuming data as array you should insert data in a new empty array.
const arr = [];
// extract upin, mtype, land from the original array
for (let item of data) {
arr.push({
upin: item.upin,
mtype: item.mtype,
land: item.land
});
}
// OR
const arr = data.map((item) => {
return {
upin: item.upin,
mtype: item.mtype,
land: item.land
};
});
You can use map and destructing method for your requirement, you can include what properties you need. I did not see land property in your data.
const result = arr.map(({ upin, mtype }) => ({
upin, mtype
}));
var arr =[{ id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2"
}, {
id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2" }]
const result = arr.map(({ upin, mtype }) => ({
upin, mtype
}));
console.log(result);
this is pure javascript and it has nothing to do with angular. you can use map function to transform arrays.
const arr2 = this.arr.map(el => ({upins: el.upins, mtyp: el.mtyp, land: el.land}));
The first answer is right. I only want to add that you can use map method for same goal. It's more comfortable for me:
const newData = data.map(x => {
return {
upin: x.upin,
mtype: x.mtype,
land: x.land
};
});
Map will check each element in the array and return new object based on element properties.

typeahead / filter / JSON parse?

Trying to 'parse/read' an external .json file on my typeahead code, but the .json file (which I cannot modify) looks like:
{"**cms_countries**":
[{"**cms_country**":
[{"**countrydisplayname**":"Afghanistan"}
,{"countrydisplayname":"Albania"} ,{"countrydisplayname":"Algeria"}
... ... ... ,{"countrydisplayname":"Zimbabwe"} ] } ,{"TotalRecords":
[ {"TotalRecords":"246"} ] } ] }
So, I think my problem is to know how to parse/read/assimilate/integrate/adopt this .json file, having
cms_countries ,
cms_country ,
and then, my countrydisplayname field on it. (have you seen the tree here ?)
This is my code:
$(document).ready(function() {
var searchablePlaces = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace("countrydisplayname"),
queryTokenizer : Bloodhound.tokenizers.whitespace,
prefetch : 'countries.json',
remote : {
url : 'countries/%QUERY.json',
wildcard : '%QUERY',
filter : function(response) { return response.cms_country; }
},
limit : 10
});
searchablePlaces.initialize();
$('#remote .typeahead').typeahead(
{
hint : true,
highlight : true,
minLength : 2
},
{
name : 'countrydisplayname',
displayKey : "countrydisplayname",
source : searchablePlaces.ttAdapter()
})
});
But of course, it is not working:
ANY hint on how to organize my filter... ? or how to do to overcome my nested .json wrappers....
OK, I've got my code working now:
$(window).load(function(){
var movies = new Bloodhound({
limit: 10,
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'countries.json',
filter: function (movies) {
return $.map(movies.cms_countries[0].cms_country, function (paises) {
return {
value: paises.countrydisplayname
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
//displayKey: 'value',
displayKey: function (toto) {
return toto.value;
},
source: movies.ttAdapter()
});
});

How to change x-axis label in Stacked Area Chart NVD3.js? [duplicate]

I have a simple line graph with data in the format:
[
{
label: "lebel1",
x: 0,
y: 128
},
{
label: "lebel1",
x: 1,
y: 128
},
....
{
label: "lebel2",
x: 25,
y: 128
},
....
{
label: "lebel8",
x: 285,
y: 128
},
....
}
and I pass this into my nvd3 object:
nv.addGraph(function()
{
var chart = nv.models.lineChart();
chart.xAxis
.axisLabel("My X-Axis")
.ticks(36)
.tickFormat(function(d) { return d; });
chart.yAxis
.axisLabel('Voltage (v)')
.tickFormat(d3.format('.02f'));
d3.select('div svg')
.datum(myData)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(function() { d3.select(gridSvgId).call(chart) });
return chart;
});
How can I have my x-axis ticks to show:
* eight labels: label1 - label8
Rather than have the grids broken up into a variable number of lines?
Try something like this
chart.xAxis.tickValues(['Label 1','Label 2','Label 3','Label 4','Label 5','Label 6','Label 7','Label 8']);
or if you want to get it from the dataset, you could try something like this,
chart.xAxis.tickValues(function(d) {
// do all you stuff and return an array
var dataset = ['Build Array from data'];
return dataset;
};)
Hope it helps

Parsing doubly nested JSON object to MongoDB

Schema for my MongoDB model:
var resultsSchema = new mongoose.Schema({
start_date: String,
end_date: String,
matches:[{
id:Number,
match_date:String,
status:String,
timer:Number,
time:String,
hometeam_id:Number,
hometeam_name:String,
hometeam_score:Number,
awayteam_id:Number,
awayteam_name:String,
awayteam_score:Number,
ht_score:String,
ft_score:String,
et_score:String,
match_events:[{
id:Number,
type:String,
minute:Number,
team:String,
player_name:String,
player_id:Number,
result:String
}]
}]
});
Example of JSON data coming from the server:
"matches":
[
{
"match_id":"1234"
"match_date":"Aug 30"
...
...
"match_events":
[
{
"event_id":"234",
"event_minute":"38",
...,
...
},
{
"event_id":"2334",
"event_minute":"40",
...,
...
}
],
{
"match_id":"454222"
"match_date":"Aug 3"
...
...
"match_events":
[
{
"event_id":"234",
"event_minute":"38",
...,
...
},
....
My current implementation works for parsing just the matches (i.e the first array). But I can't seem to access the inner array properly.
async.waterfall([
function(callback) {
request.get('http://football-api.com/api/?Action=fixtures&APIKey=' + apiKey + '&comp_id=' + compId +
'&&from_date=' + lastWeek_string + '&&to_date=' + today_string, function(error, response, body) {
if (error) return next(error);
var parsedJSON = JSON.parse(body);
var matches = parsedJSON.matches;
var events = parsedJSON.matches.match_events;
var results = new Results({
start_date: lastWeek_string,
end_date: today_string,
matches:[]
});
_.each(matches, function(match) {
results.matches.push({
id: match.match_id,
match_date: match.match_formatted_date,
status:match.match_status,
timer:match.match_timer,
hometeam_id:match.match_localteam_id,
hometeam_name:match.match_localteam_name,
hometeam_score:match.match_localteam_score,
awayteam_id:match.match_visitorteam_id,
awayteam_name:match.match_visitorteam_name,
awayteam_score:match.match_visitorteam_score,
ht_score:match.match_ht_score,
ft_score:match.match_ft_score,
et_score:match.match_et_score,
match_events:[]
});
});
_.each(events, function(event) {
results.matches.match_events.push({
id:event.event_id,
type:event.event_type,
minute:event.event_minute,
team:event.event_team,
player_name:event.event_player,
player_id:event.event_player_id,
result:event.event_result
});
});
I understand that the second _.each loop should be iterating for every match, since very match has it's own events subarray. I'm just not sure how to structure this and have been struggling with it for a while.
I tried nesting that loop inside the _.each(matches, function(match) { loop but that didn't work.
Thank you.
Edit: How could I get this to work?
var results = new Results({
start_date: lastWeek_string,
end_date: today_string,
matches:[
match_events: []
]
});
Because then as #zangw says I could construct the match_events array first, append it to matches, and so on.