Convert json data to object - javascript

Good Day Developers!
I'm facing issue in JSON object received from MVC controller to AJAX success request.
The response which received is below.
[
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
]
But i want to make it like below.
{
"name": [
"ERP Developer",
"Software Engineer"
],
"Value": [
5,
10
]
}
Problem: Because i'm creating Bar chart using ECHARTS library but i want series name instead of number please see below image for reference.
function loadBarChart(data,title = "JobData",subtext = "Artistic Milliners") {
//var BarDBData = data;
var BarDBData = data;
//var BarDBData = JSON.parse('{"name":["ERP Developer","TEST"],"test":[5,10]}');
console.log(BarDBData);
var chartDom = document.getElementById('BarChart');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: title,
subtext: subtext
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
// prettier-ignore
//data: ["ERP Developer", "Software Engineer"],
data: BarDBData,
axisLabel: { interval: 0, rotate: 30 }
}
],
yAxis: [
{
type: 'value'
}
],
dataZoom: [
{
show: true,
start: 04,
end: 100
},
{
type: 'inside',
start: 44,
end: 100
},
{
show: true,
yAxisIndex: 0,
filterMode: 'empty',
width: 30,
height: '80%',
showDataShadow: false,
left: '93%'
}
],
series: [
{
name: "test",
type: 'bar',
data: BarDBData,
//data: [2.0, 4.9, 4, 9, 4],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
}
}
]
};
option && myChart.setOption(option);
}

you can just map through array and extract values into another array
const result = {}
const arr = [{"name":"ERP Developer","value":2},{"name":"Software Engineer","value":2},{"name":"Dot Net Developer","value":2},{"name":"Apex Developer","value":0},{"name":"test","value":1}]
arr.forEach(row => {
for (let i in row) {
if (result[i]) {
result[i].push(row[i])
} else {
result[i] = [row[i]]
}
}
})
console.log(result)

Just reduce() it into the desired shape:
const response = [
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
];
const mapped = response.reduce(
(acc,x) => {
acc.name.push( x.name );
acc.Value.push( x.value );
return acc;
},
{ name: [], Value: [] }
);

Related

SAPUI5 line chart returning weird output

I am using northwind oData model and using the "SummaryByYear" model to create a line chart. The data looks as follows (for easier representation, only 4 entries are shown):
{
"results": [
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10248)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-16T00:00:00.000Z",
"OrderID": 10248,
"Subtotal": "440.00"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10249)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-10T00:00:00.000Z",
"OrderID": 10249,
"Subtotal": "1863.40"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10250)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-12T00:00:00.000Z",
"OrderID": 10250,
"Subtotal": "1552.60"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10251)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-15T00:00:00.000Z",
"OrderID": 10251,
"Subtotal": "654.06"
}
]
}
following is the XML view for Chart:
<chart:ChartContainer id="chartContainer" showFullScreen="true" showZoom="false" title="Sales Summary (by Year)">
<chart:ChartContainerContent>
<chart:content>
<viz:VizFrame id="lineChart" width="auto" uiConfig="{applicationSet:'fiori'}">
</viz:VizFrame>
</chart:content>
</chart:ChartContainerContent>
</chart:ChartContainer>
and this is the controlles onInit function:
onInit: function () {
var northwind = this.getOwnerComponent().getModel("northwind");
var that = this;
northwind.read("/Summary_of_Sales_by_Years", {
method: "GET",
success: function (resp) {
resp["results"].forEach(item => {
item.Subtotal = item.Subtotal.toString().slice(0, -2)
});
var summaryByYear = new JSONModel({
"results": resp["results"]
})
var lineChart = that.getView().byId("lineChart");
lineChart.setVizType('line');
lineChart.setUiConfig({
applicationSet: 'fiori',
});
var oDataset = new FlattenedDataset({
dimensions: [{
axis: 1,
name: 'Year',
value: '{ShippedDate}',
datatype: "date"
}, ],
measures: [{
name: 'Subtotal',
value: '{Subtotal}',
}],
data: {
path: '/results',
},
});
lineChart.setDataset(oDataset);
lineChart.setModel(summaryByYear);
var feedValueAxis = new FeedItem({
uid: 'valueAxis',
type: 'Measure',
values: ['Subtotal'],
}),
feedCategoryAxis = new FeedItem({
uid: 'categoryAxis',
type: 'Dimension',
values: ['Year'],
});
lineChart.addFeed(feedValueAxis);
lineChart.addFeed(feedCategoryAxis);
lineChart.setVizProperties({
general: {
layout: {
padding: 0.04,
},
},
plotArea: {
window: {
start: 'firstDataPoint',
end: 'lastDataPoint'
}
},
valueAxis: {
label: {
formatString: 'axisFormat',
},
title: {
visible: false,
},
},
categoryAxis: {
title: {
visible: false,
},
},
plotArea: {
dataLabel: {
visible: true,
formatString: 'datalabelFormat',
style: {
color: null,
},
},
},
legend: {
title: {
visible: false,
},
},
title: {
visible: false,
text: 'Summary of Sales (by year)',
},
levels: ['month', 'day', 'year'],
interval: {
unit: ''
}
});
}
});
}
following is the result:
I am getting the date in raw timestamp format instead of year and month and also there are weird texts such as "5atalabelfor9at". What am I doing wrong here and please point me to the correct docs if I am missing some kind of config, thanks.

How to add data to a Tooltip in a echart graph

i have this bar graph made with echar, and i want to add information to the tooltip that it shows when you select a bar in the graph, how can i to do that?
this is the graphic code:
option: {
title: {
text: "Unidades que Necesitan Mantenimiento por Kilometro",
//subtext: "Living Expenses in Shenzhen",
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
},
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
xAxis: [
{
type: "category",
data: [],
axisTick: {
alignWithLabel: true,
},
},
],
yAxis: [
{
type: "value",
},
{
type: "value",
},
],
series: [
{
name: "Kilometraje Excedido",
type: "bar",
barWidth: "60%",
data: [],
},
],
},
here i load actually the information from my request, i want to load the information from Año_del_Modelo and Fecha_del_Ultimo_Servis also i want to add a label that says "Modelo", and "Ultimo Servis":
async obtenerUnidadesMantenimientoImportante() {
var respuesta;
this.url =
this.urlBase + "reporte/obtenerunidadesmantenimientoimportante";
const config = {
headers: {
Authorization: `Bearer ${sessionStorage.getItem("Token")}`,
},
};
respuesta = await this.$http
.get(this.url, config)
.then((response) => response.data);
var i = 0;
while (i < 9) {
this.modelos.push(respuesta[i].Año_del_Modelo);
this.ultMantenimientos.push(respuesta[i].Fecha_del_Ultimo_Servis);
this.option.xAxis[0].data.push(respuesta[i].Unidad);
this.option.series[0].data.push(
respuesta[i].Km_Restante_de_Proximo_Servis * -1
);
i++;
}
},

Echarts:My pie charts block my line chart while I'm intended to bind them together

How can I bind pie chart and line chart together rather than appear one by one? And the pie charts which appear later than line chart will block the line chart. Is there any chance the pie and line can appear together in the end?
The current situation is that
at the beginning,and then.
This is the JS code.
var dom2 = document.getElementById('demo');
var chart = echarts.init(dom2);
var option = {
title: {
text: '中药与疾病'
},
tooltip: {},
legend: {
data: ['中药', '疾病']
},
xAxis: {
data: []
},
yAxis: [
{},
{}
],
series: [
{
name: '中药',
type: 'line',
data: [],
yAxisIndex: 0
},
{
name: '疾病',
type: 'line',
data: [],
yAxisIndex: 1
}
]
}
chart.setOption(option);
$.get('https://gist.githubusercontent.com/Linya-gzl/4d4f388e1b0e3d8e05c38f875b94a97c/raw/8c121acbfaf4aac9eccaf6b81cd1b3614203c185/demo1.json').done(function (data) {
dataArr = JSON.parse(data);
console.log(dataArr);
chart.setOption({
xAxis: {
data: dataArr.map(row => row['categories'])
},
series: [{
name: '中药',
data: dataArr.map(row => row['value1'])
},
{
name: '疾病',
data: dataArr.map(row => row['value2'])
}]
});
function buildPieSeries() {
var len = dataArr.length;
for (var i = 0; i < len; i++) {
option.series.push({
type: 'pie',
radius: 15,
center: [110 + 90 * i, dataArr[i].value2 - 100],
label: {
show: true,
textStyle: {
fontSize: 8
}
},
data: [
{ value: dataArr[i].value1, name: '黄连' },
{ value: dataArr[i].value2, name: '黄芩' },
]
})
}
chart.setOption(option, true);
}
setTimeout(buildPieSeries, 1000);
});
and
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div id="demo" style="width: 600px;height:400px;"></div>
I changed your code a bit in the series insertion part, by my opinion need inserting series completely because partial inserts sometimes cause problems with merging data. Also I fixed coordinate calculation, more correct way take the already calculated coordinates from line if they the same.
document.addEventListener("DOMContentLoaded", e => {
var targetNode = document.querySelector('#chartNode');
var chartInstance = echarts.init(targetNode);
var option = {
title: { text: '中药与疾病' },
tooltip: {},
legend: { data: ['中药', '疾病'] },
xAxis: { data: [] },
yAxis: [
{},
{}
],
series: [
{
name: '中药',
type: 'line',
data: [],
yAxisIndex: 0
},
{
name: '疾病',
type: 'line',
data: [],
yAxisIndex: 1
}
]
}
chartInstance.setOption(option);
$.get('https://gist.githubusercontent.com/Linya-gzl/4d4f388e1b0e3d8e05c38f875b94a97c/raw/8c121acbfaf4aac9eccaf6b81cd1b3614203c185/demo1.json').done(function (data) {
dataArr = JSON.parse(data);
chartInstance.setOption({
xAxis: {
data: dataArr.map(row => row['categories'])
},
series: [{
name: '中药',
data: dataArr.map(row => row['value1'])
},
{
name: '疾病',
data: dataArr.map(row => row['value2'])
}]});
pieSeries = chartInstance.getOption().series;
function buildPieSeries() {
var len = dataArr.length;
for (var i = 0; i < len; i++) {
pieSeries.push({
type: 'pie',
radius: 15,
z: 10,
center: chartInstance.getModel().getSeriesByName('中药')[0].getData().getItemLayout(i),
// center: [110 + 90 * i, dataArr[i].value2 - 100],
label: {
show: true,
textStyle: {
fontSize: 8
}},
data: [
{ value: dataArr[i].value1, name: '黄连' },
{ value: dataArr[i].value2, name: '黄芩' },
]
})
};
chartInstance.setOption({ series: pieSeries });
}
setTimeout(() => buildPieSeries(), 1000);
});
});
<script src="https://cdn.jsdelivr.net/npm/echarts#4.7.0/dist/echarts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chartNode" style="width: 600px;height:400px;"></div>

Proper format of json for Highchart.js with multiple series

I have examples json data for Higcharts USD currency:
https://cdn.jsdelivr.net/gh/highcharts/highcharts#v7.0.0/samples/data/usdeur.json
So i added simply one value to data, there not show in a chart.
[
[
1167609600000,
50,
30
],
[
1167609600001,
60,
40
],
[
1167609600002,
70,
50
]
]
My code:
function myFunction() { Highcharts.getJSON(
'http://192.168.0.157/log1.json', function (data) {
Highcharts.chart('container', {
chart: {
zoomType: 'x', backgroundColor:"#e7ecea"
},
title: {
text: 'Pomiary'
},
subtitle: {
text: document.ontouchstart === undefined ?
'select' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'speed',
data: data
}, {
type: 'area',
name: 'speed2',
data: data
}]
}); } );
};
How i can add next series?
The simplest way is to use keys property:
series: [{
data: data
}, {
keys: ['x', 'someValue', 'y'],
data: data
}]
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4797/
API Reference: https://api.highcharts.com/highcharts/series.line.keys

how to implement dragging of graphic elements in echarts graph chart with vue

Key Words: vue echarts graph drag
I want to make a graph chart with draggable nodes.
I use graphic to create circles with the dragging function on nodes.
there are two bugs:
When I move one node, the other nodes will move too.
Although I update the option immediately when the data change, but the chart always change a few seconds later.
You can init a vue-project with vue-cli3 and npm install echarts.
Then you can copy the codes to instead of the App.vue.
<template>
<div id="app">
<div id="charts" ref="chart" style="height:70vh;"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data () {
return {
myChart: null,
option: {},
graph: {
nodes: [
{
name: 'Node1',
x: 300,
y: 300
},
{
name: 'Node2',
x: 800,
y: 300
},
{
name: 'Node3',
x: 550,
y: 100
},
{
name: 'Node4',
x: 550,
y: 500
}
],
links: [
{
source: 0,
target: 1,
symbolSize: [5, 20],
label: {
normal: {
show: true
}
},
lineStyle: {
normal: {
width: 5,
curveness: 0.2
}
}
},
{
source: 'Node2',
target: 'Node1',
label: {
normal: {
show: true
}
},
lineStyle: {
normal: { curveness: 0.2 }
}
},
{
source: 'Node1',
target: 'Node3'
},
{
source: 'Node2',
target: 'Node3'
},
{
source: 'Node2',
target: 'Node4'
},
{
source: 'Node1',
target: 'Node4'
}
]
}
}
},
mounted () {
this.initChart()
this.renderChart()
},
methods: {
initChart () {
this.myChart = echarts.init(document.getElementById('charts'));
},
renderChart() {
this.myChart.showLoading();
this.formatOption();
this.initDrag();
},
formatOption () {
this.option = {
title: {
text: 'Graph 简单示例'
},
tooltip: {},
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
series : [
{
type: 'graph',
layout: 'none',
symbolSize: 50,
roam: 'scale',
label: {
normal: {
show: true
}
},
edgeSymbol: ['circle', 'arrow'],
edgeSymbolSize: [4, 10],
edgeLabel: {
normal: {
textStyle: {
fontSize: 20
}
}
},
nodes: this.graph.nodes,
links: this.graph.links,
lineStyle: {
normal: {
opacity: 0.9,
width: 2,
curveness: 0
}
}
}
]
};
this.myChart.hideLoading();
this.myChart.setOption(this.option, true);
},
initDrag () {
this.option.graphic = echarts.util.map(this.graph.nodes, (item, dataIndex) => {
return {
type: 'circle',
position: this.myChart.convertToPixel({seriesIndex: 0}, [item.x, item.y]),
shape: {
r: 10
},
// invisible: true,
style: {
fill: 'blue'
},
draggable: true,
ondrag: echarts.util.curry(this.onPointDragging, dataIndex),
z: 100
}
});
this.myChart.setOption(this.option);
window.addEventListener('resize', this.updatePosition);
},
updatePosition () {
this.myChart.setOption({
graphic: echarts.util.map(this.graph.nodes, (item, dataIndex) => {
return {
position: this.myChart.convertToPixel({seriesIndex: 0}, [item.x, item.y])
};
})
});
},
onPointDragging (dataIndex, event) {
let pos = this.myChart.convertFromPixel({seriesIndex: 0}, [event.offsetX, event.offsetY]) // 将graphic的像素坐标转化为坐标系坐标
this.graph.nodes[dataIndex].x = pos[0] // 将新的坐标系坐标赋值给node
this.graph.nodes[dataIndex].y = pos[1]
this.myChart.setOption({
series: {
nodes: this.graph.nodes
}
})
this.updatePosition()
}
}
}
</script>
<style scoped>
#charts {
flex: 1;
border: 1px solid;
box-shadow: 0 0 20px rgba(18,208,253,.5);
}
</style>

Categories