I managed to implement a chart of prices over time, but now I want to filter the chart based on the category of the items. I was planning on a pie chart to display the items categories and when a specific one is selected the line chart is updated only to show items associated with that.
Let's say this is my data:
{"date": "06/01/2023 16:45", "item": "Apple", "cat": "Fruit", "price": "9.00"}
{"date": "06/01/2023 16:45", "item": "Orange", "cat": "Fruit", "price": "8.00"}
{"date": "06/01/2023 16:45", "item": "Pear", "cat": "Fruit", "price": "7.00"}
{"date": "06/01/2023 16:45", "item": "Water", "cat": "Drink", "price": "2.00"}
{"date": "06/01/2023 16:45", "item": "Soda", "cat": "Drink", "price": "3.00"}
{"date": "07/01/2023 16:45", "item": "Apple", "cat": "Fruit", "price": "9.50"}
{"date": "07/01/2023 16:45", "item": "Orange", "cat": "Fruit", "price": "8.50"}
{"date": "06/01/2023 16:45", "item": "Pear", "cat": "Fruit", "price": "7.50"}
{"date": "07/01/2023 16:45", "item": "Water", "cat": "Drink", "price": "2.50"}
{"date": "07/01/2023 16:45", "item": "Soda", "cat": "Drink", "price": "3.50"}
Now if I click on the Fruit part of the chart:
I want my line chart to only display the data for Apple, Orange, and Pear. I was not able to find any examples on Chart.Js 4 documentation on how to make linked charts. Any useful examples to share?
There are probably some other ways (maybe even some nicer ways), but this is how I would do this quick and dirty.
In the onClick event I would set the data for the other Chart and than just call updateon the second chart. (link to the documentation)
Here a demo, how I would do this:
(Click on the pieChart to see the LineChart)
// Original Data
let dataSet = [
{"date": "06/01/2023 16:45", "item": "Apple", "cat": "Fruit", "price": "9.00"},
{"date": "06/01/2023 16:45", "item": "Orange", "cat": "Fruit", "price": "8.00"},
{"date": "06/01/2023 16:45", "item": "Pear", "cat": "Fruit", "price": "7.00"},
{"date": "06/01/2023 16:45", "item": "Water", "cat": "Drink", "price": "2.00"},
{"date": "06/01/2023 16:45", "item": "Soda", "cat": "Drink", "price": "3.00"},
{"date": "07/01/2023 16:45", "item": "Apple", "cat": "Fruit", "price": "9.50"},
{"date": "07/01/2023 16:45", "item": "Orange", "cat": "Fruit", "price": "8.50"},
{"date": "06/01/2023 16:45", "item": "Pear", "cat": "Fruit", "price": "7.50"},
{"date": "07/01/2023 16:45", "item": "Water", "cat": "Drink", "price": "2.50"},
{"date": "07/01/2023 16:45", "item": "Soda", "cat": "Drink", "price": "3.50"}
]
// pre split data
let drinkData = dataSet.filter(n => n.cat =='Drink')
let fruitData = dataSet.filter(n => n.cat =='Fruit')
let fruitDataSets = []
let drinkDataSets = []
let lineChartColors = ['#4BC0C0', '#FF9F40', '#9966FF']
// prepare Data for LineChart -- START
let formatedData = fruitData.reduce((p,c) => {
if(!p[c.item]){
p[c.item] = []
}
p[c.item].push({x: new Date(c.date), y: parseFloat(c.price), label: c.item})
return p
}, {});
Object.values(formatedData).forEach((n, i) => fruitDataSets.push({
data: n,
label: n[0].label,
backgroundColor: lineChartColors[i],
borderColor: lineChartColors[i]
}));
formatedData = drinkData.reduce((p,c) => {
if(!p[c.item]){
p[c.item] = []
}
p[c.item].push({x: new Date(c.date), y: parseFloat(c.price), label: c.item})
return p
}, {});
Object.values(formatedData).forEach((n, i) => drinkDataSets.push({
data: n,
label: n[0].label,
backgroundColor: lineChartColors[i],
borderColor: lineChartColors[i]
}));
// prepare Data for LineChart -- END
// create data for the pieChart
let preparedPieData = dataSet.reduce((p,c) => {
p[c.cat]++
return p
}, { Drink:0, Fruit: 0});
const pieData = {
// create labels for the pieChart
labels: Object.keys(preparedPieData),
datasets: [{
data: Object.values(preparedPieData),
backgroundColor: ['#35A2EB', '#FF6283'],
borderWidth: 1,
}],
};
let lineData = {
datasets: [],
};
// PieChart Configuration
const config = {
type: 'pie',
data: pieData,
options: {
maintainAspectRatio: false,
onClick: function(e, item){
lineData.datasets = item[0].index == 0 ? drinkDataSets : fruitDataSets
lineChart.update();
}
}
};
// LineChart Configuration
const config2 = {
type: 'line',
data: lineData,
options: {
maintainAspectRatio: false,
scales: {
x: {
type: 'time',
time: {
unit: 'week'
}
}
}
}
};
new Chart(
document.getElementById('chart1'),
config
);
let lineChart = new Chart(
document.getElementById('chart2'),
config2
);
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.js"></script>
<script src="//cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="//cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
<div class="chart" style="float:left;height:184px; width:250px;">
<canvas id="chart1" ></canvas>
</div>
<div class="chart" style="float:left;height:184px; width:250px;">
<canvas id="chart2" ></canvas>
</div>
Related
I have searched a lot regarding filter of product data using checkbox but couldn't able to find the right answer for my issue.
Problem: I'm making a product filter page using checkbox in react but could not found the proper way to filter the true value of object key.
ie. I have to only filter object key value === true. Below array object is after checkbox selection before the selection it will be falsy value.
const category = [
{
"type":"Color",
"options":[
{
"key":"Red",
"value":true
},
{
"key":"Blue",
"value":false
},
{
"key":"Green",
"value":true
}
]
},
{
"type":"Gender",
"options":[
{
"key":"Men",
"value":true
},
{
"key":"Women",
"value":false
}
]
},
{
"type":"Price",
"options":[
{
"key":"0 - Rs. 250",
"from":0,
"to":250,
"value":false
},
{
"key":"Rs. 251 - 450",
"from":251,
"to":450,
"value":true
},
{
"key":"Rs. 451 & above",
"from":451,
"to":"Number.MAX_VALUE",
"value":false
}
]
},
{
"type":"Type",
"options":[
{
"key":"Polo",
"value":false
},
{
"key":"Hoodie",
"value":false
},
{
"key":"Basic",
"value":true
}
]
}
]
const productData = [
{
"id": 1,
"name": "Black Polo",
"type": "Polo",
"price": 250,
"currency": "INR",
"color": "Black",
"gender": "Men",
"quantity": 3
},
{
"id": 2,
"name": "Blue Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Blue",
"gender": "Women",
"quantity": 3
},
{
"id": 3,
"name": "Pink Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Pink",
"gender": "Women",
"quantity": 6
},
{
"id": 4,
"name": "Black Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Black",
"gender": "Men",
"quantity": 2
},
{
"id": 5,
"name": "Green Polo",
"type": "Polo",
"price": 250,
"currency": "INR",
"color": "Green",
"gender": "Men",
"quantity": 1
},
{
"id": 6,
"name": "Green Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Green",
"gender": "Women",
"quantity": 1
},
{
"id": 7,
"name": "Blue Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Blue",
"gender": "Women",
"quantity": 2
},
{
"id": 8,
"name": "Black Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Black",
"gender": "Women",
"quantity": 5
}]
Now,I need filtered product data from the above category data and product-data.
Here's my Codesandbox link for this.
Below the input data:
[
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
},
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
I would like a resulting object using a single AlaSQL query:
{
"jim": {
"color": "blue",
"age": "22"
},
"sam": {
"color": "blue",
"age": "33"
},
"eddie": {
"color": "green",
"age": "77"
}
}
Is there any way to achieve it one shot with a AlaSQL query ?
This would allow to easily find contact info (e.g. data["eddie"].age)
The closest way I found is this:
var res = alasql('SELECT name, ARRAY(_) AS details FROM ? GROUP BY name', [data]);
but I still obtain an array under this format:
[
{
"name": "jim",
"details": [{
"color": "blue",
"age": "22"
}],
},
{
"name": "Sam",
"details": [{
"color": "blue",
"age": "33"
}],
},
{
"name": "eddie",
"details": [{
"color": "green",
"age": "77"
}]
}
]
What would be the fatest and efficient way to achieve the goal ?
I build FusionCharts multilevelpie graph. But huge indents appear.
500 x 500
With a decrease in space, the graph is greatly reduced.
padding 1
100% x 100%
When doing a full size chart, the indents become too large.
padding 2
When I reduce the space of the graph, the graph becomes too small.
My code:
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
type: 'multilevelpie',
renderAt: 'chart-container',
width: '500',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "",
"subcaption": "",
"showPlotBorder": "1",
"piefillalpha": "60",
"pieborderthickness": "2",
"hoverfillcolor": "#CCCCCC",
"piebordercolor": "#FFFFFF",
"hoverfillcolor": "#CCCCCC",
"numberprefix": "#",
"plottooltext": "$label",
"theme": "fusion",
},
"category": {{ pie }},
}
}
);
fusioncharts.render();
});
You can adjust the size of the outer part of the pie using pieRadius attribute at the chart object level, take a look at this sample -
FusionCharts.ready(function() {
var topProductsChart = new FusionCharts({
type: 'multilevelpie',
renderAt: 'chart-container',
id: "myChart",
width: '400',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"theme": "fusion",
"caption": "Split of Top Products Sold",
"subCaption": "Last Quarter",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"baseFontColor": "#333333",
"baseFont": "Helvetica Neue,Arial",
"basefontsize": "9",
"subcaptionFontBold": "0",
"bgColor": "#ffffff",
"canvasBgColor": "#ffffff",
"showBorder": "0",
"showShadow": "0",
"showCanvasBorder": "0",
"pieFillAlpha": "60",
"pieBorderThickness": "2",
"hoverFillColor": "#cccccc",
"pieBorderColor": "#ffffff",
"useHoverColor": "1",
"showValuesInTooltip": "1",
"showPercentInTooltip": "0",
"numberPrefix": "$",
"plotTooltext": "$label, $$valueK, $percentValue",
"pieRadius": "170"
},
"category": [{
"label": "Sales by category",
"color": "#ffffff",
"value": "150",
"category": [{
"label": "Food & {br}Beverages",
"color": "#f8bd19",
"value": "55.5",
"category": [{
"label": "Breads",
"color": "#f8bd19",
"value": "11.1"
},
{
"label": "Juice",
"color": "#f8bd19",
"value": "27.75"
},
{
"label": "Noodles",
"color": "#f8bd19",
"value": "9.99"
},
{
"label": "Seafood",
"color": "#f8bd19",
"value": "6.66"
}
]
},
{
"label": "Apparel &{br}Accessories",
"color": "#e44a00",
"value": "42",
"category": [{
"label": "Sun Glasses",
"color": "#e44a00",
"value": "10.08"
},
{
"label": "Clothing",
"color": "#e44a00",
"value": "18.9"
},
{
"label": "Handbags",
"color": "#e44a00",
"value": "6.3"
},
{
"label": "Shoes",
"color": "#e44a00",
"value": "6.72"
}
]
},
{
"label": "Baby {br}Products",
"color": "#008ee4",
"value": "22.5",
"category": [{
"label": "Bath &{br}Grooming",
"color": "#008ee4",
"value": "9.45"
},
{
"label": "Feeding",
"color": "#008ee4",
"value": "6.3"
},
{
"label": "Diapers",
"color": "#008ee4",
"value": "6.75"
}
]
},
{
"label": "Electronics",
"color": "#33bdda",
"value": "30",
"category": [{
"label": "Laptops",
"color": "#33bdda",
"value": "8.1"
},
{
"label": "Televisions",
"color": "#33bdda",
"value": "10.5"
},
{
"label": "SmartPhones",
"color": "#33bdda",
"value": "11.4"
}
]
}
]
}]
}
});
topProductsChart.render();
});
Here is a live demo - http://jsfiddle.net/cebu68vt/
I have object and I am trying to push data into it, but I am getting the error "push is not a function".
Here's my object:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
}
I want to push:
var modal = {
'custid': '1',
'packcode': '22'
};
item.push(modal);
console.log(item);
Here's my expected result:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first",
'custid': '1',
'packcode': '22'
};
How do I do that?
You don't push into objects, you push into arrays.
Based on what you've said you want, you do this:
item.custid = '1';
item.packcode = '22';
E.g., just assign properties to the object.
In ES2015, you could use Object.assign if having modal be separate is important:
var modal = {custid: '1', packcode: '22'};
Object.assign(item, modal);
...but I don't see a need for it here, and note that there's no ongoing link between modal and item.
Live Example:
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
};
item.custid = '1';
item.packcode = '22';
// Note: Just using JSON for *display*
document.body.innerHTML =
"<pre>" + JSON.stringify(item, null, 2) + "</pre>";
Or with Object.assign (requires an up-to-date browser or a shim):
var item = {
"_id": {
"$oid": "asdf976"
},
"Categories": [{
"mainmodels": [{
"submodels": [{
"price": "2000",
"submodelname": "lumia021",
"Remainingphones": "0",
"Bookedphones": "0",
"Numofphones": "10"
}, {
"price": "2000",
"submodelname": "lumia341",
"Remainingphones": "5",
"Bookedphones": "5",
"Numofphones": "10"
}
],
"Status": "Active",
"modelname": "lumia",
"fromdate": "2016-04-01T16:39:12.051Z",
"todate": "2016-04-31T19:19:44.051Z"
}],
"brand": "nokia"
}],
"rank": "1",
"name": "first"
};
var modal = {
custid: '1',
packcode: '22'
};
Object.assign(item, modal);
// Note: Just using JSON for *display*
document.body.innerHTML =
"<pre>" + JSON.stringify(item, null, 2) + "</pre>";
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to parse the Weather API (URL) city name, temperature, etc.
My JSON data is the following:
{
"data": {
"current_condition": [{
"cloudcover": "25",
"humidity": "70",
"observation_time": "04:21 PM",
"precipMM": "0.3",
"pressure": "1007",
"temp_C": "30",
"temp_F": "86",
"visibility": "4",
"weatherCode": "113",
"weatherDesc": [{
"value": "Clear"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"}],
"winddir16Point": "S",
"winddirDegree": "180",
"windspeedKmph": "7",
"windspeedMiles": "4"}],
"request": [{
"query": "Ahmedabad, India",
"type": "City"}],
"weather": [{
"date": "2012-09-18",
"precipMM": "2.1",
"tempMaxC": "32",
"tempMaxF": "89",
"tempMinC": "25",
"tempMinF": "76",
"weatherCode": "176",
"weatherDesc": [{
"value": "Patchy rain nearby"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png"}],
"winddir16Point": "SSW",
"winddirDegree": "203",
"winddirection": "SSW",
"windspeedKmph": "12",
"windspeedMiles": "8"},
{
"date": "2012-09-19",
"precipMM": "3.4",
"tempMaxC": "32",
"tempMaxF": "89",
"tempMinC": "25",
"tempMinF": "76",
"weatherCode": "176",
"weatherDesc": [{
"value": "Patchy rain nearby"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png"}],
"winddir16Point": "SW",
"winddirDegree": "223",
"winddirection": "SW",
"windspeedKmph": "12",
"windspeedMiles": "7"}]
}
}
How do I parse this data and get city name and temperature..I have no idea..Thanks in adavance.
=============== OutPut =======================
i want to fetch data like this and Set on Textbox
Date 2012-09-18 2012-09-19
tempMaxC 32 32
tempMinC 25 25
tempMaxF 89 89
tempMinF 76 76
If you've retrieved this JSON as a string, then pass this string to JSON.parse()* and then access to retrieved value as to a regular JavaScript object:
var jsonStr = '{ "data": { "current_condition": [ {"cloudcover": "25", "humidity": "70", "observation_time": "04:21 PM", "precipMM": "0.3", "pressure": "1007", "temp_C": "30", "temp_F": "86", "visibility": "4", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "S", "winddirDegree": "180", "windspeedKmph": "7", "windspeedMiles": "4" } ], "request": [ {"query": "Ahmedabad, India", "type": "City" } ], "weather": [ {"date": "2012-09-18", "precipMM": "2.1", "tempMaxC": "32", "tempMaxF": "89", "tempMinC": "25", "tempMinF": "76", "weatherCode": "176", "weatherDesc": [ {"value": "Patchy rain nearby" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png" } ], "winddir16Point": "SSW", "winddirDegree": "203", "winddirection": "SSW", "windspeedKmph": "12", "windspeedMiles": "8" }, {"date": "2012-09-19", "precipMM": "3.4", "tempMaxC": "32", "tempMaxF": "89", "tempMinC": "25", "tempMinF": "76", "weatherCode": "176", "weatherDesc": [ {"value": "Patchy rain nearby" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png" } ], "winddir16Point": "SW", "winddirDegree": "223", "winddirection": "SW", "windspeedKmph": "12", "windspeedMiles": "7" } ] }}',
jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.data.current_condition[0].temp_F);
Otherwise, if you've retrieved this JSON e.g. as a parameter of some jQuery $.ajax() success callback and it's already an object, you don't need to call JSON.parse(), but just retrieve object's values directly:
$.getJSON("http://example.com/weather.json", function(jsonObj) {
// The response string is already parsed with $.parseJSON(),
// so you don't need to parse it yourself.
// Therefore just go ahead and access the properties of JavaScript object.
console.log(jsonObj.data.current_condition[0].temp_F);
});
* If you're intended to support older browsers (e.g. IE7) that does not support JSON.parse/stringify, you'll need to include JSON library.
UPDATE:
DEMO for particular case