JavaScript
x
33
33
1
{
2
"chartOptions": {
3
"type": "line",
4
"isStacked": false,
5
"minValue": 0,
6
"maxValue": 600000,
7
"filled": false,
8
"showAxis": true,
9
"chartLabels":[
10
"May 23",
11
"May 24",
12
"May 25",
13
"May 26",
14
"May 27",
15
"May 28"
16
],
17
"chartDatasets": [
18
{
19
"label": "Mentions",
20
"backgroundColor": "rgb(81, 45, 168)",
21
"stack": "Stack 0",
22
"data": [
23
1100,
24
800,
25
750,
26
1200,
27
400,
28
600
29
]
30
}
31
]
32
},
33
Thats the original array I have from backend and now I want to build something like this:
JavaScript
1
2
1
const data = { labels: ['May 23', 'May 24', 'May 25', 'May 26', 'May 27', 'May 28'], datasets: [{ label: 'Mentions', borderDash: [5, 3], data: [6500, 5900, 8000, 8100, 5600, 10000] }] }
2
So the chartDatasets will be datasets and the chartLabels will be labels.. I think this is pretty easy but I don’t know how I can do it.
I’m saving the original array in state so..
Thanks
Advertisement
Answer
If you have to modify single time you can simply assign in object like this:
JavaScript
1
39
39
1
const data = {
2
"chartOptions": {
3
"type": "line",
4
"isStacked": false,
5
"minValue": 0,
6
"maxValue": 600000,
7
"filled": false,
8
"showAxis": true,
9
},
10
"chartLabels":[
11
"May 23",
12
"May 24",
13
"May 25",
14
"May 26",
15
"May 27",
16
"May 28"
17
],
18
"chartDatasets": [
19
{
20
"label": "Mentions",
21
"backgroundColor": "rgb(81, 45, 168)",
22
"stack": "Stack 0",
23
"data": [
24
1100,
25
800,
26
750,
27
1200,
28
400,
29
600
30
]
31
}
32
]
33
}
34
35
const modifiedData = {
36
labels:data.chartLabels,
37
datasets:data.chartDatasets,
38
}
39
console.log(modifiedData)
updated according to your requirement adding extra key in data set.
JavaScript
1
39
39
1
const data = {
2
"chartOptions": {
3
"type": "line",
4
"isStacked": false,
5
"minValue": 0,
6
"maxValue": 600000,
7
"filled": false,
8
"showAxis": true,
9
},
10
"chartLabels":[
11
"May 23",
12
"May 24",
13
"May 25",
14
"May 26",
15
"May 27",
16
"May 28"
17
],
18
"chartDatasets": [
19
{
20
"label": "Mentions",
21
"backgroundColor": "rgb(81, 45, 168)",
22
"stack": "Stack 0",
23
"data": [
24
1100,
25
800,
26
750,
27
1200,
28
400,
29
600
30
]
31
}
32
]
33
}
34
35
const modifiedData = {
36
labels:data.chartLabels,
37
datasets:data.chartDatasets.map(set => ({set, yAxisID:"bar-y-axis"})),
38
}
39
console.log(modifiedData)