Translating objects in nodeJS - javascript

I have the following object that I need to transform into a slightly different format. I'm pretty sure I can use nodes native map function to translate it. e.g.
var animals = [
[ 'cats', 1726, 1143, 10, 105, 2382, 0 ],
[ 'dogs', 640, 0, 0, 0, 0, 0 ],
[ 'cows' 13509, 0, 3, 1, 196939, 19 ],
[ 'sheep', 1573, 1084, 10, 105, 2266, 0 ]
]
Into this format:
new_animals = [{
name: 'cats',
data: [1726, 1143, 10, 105, 2382, 0]
}, {
name: 'dogs',
data: [640, 0, 0, 0, 0, 0]
}, {
name: 'cows',
data: [13509, 0, 3, 1, 196939, 19]
},
{
name: 'sheep',
data: [1573, 1084, 10, 105, 2266, 0]
}]

Using ES2015 features:
const newAnimals = animals.map(([name, ...data]) => ({ name, data }));
Without ES2015 features:
var newAnimals = animals.map(function (animal) {
return {
name: animal[0],
data: animal.slice(1)
};
});

its actually quite simple:
var animals = [
['cats', 1726, 1143, 10, 105, 2382, 0],
['dogs', 640, 0, 0, 0, 0, 0],
['cows', 13509, 0, 3, 1, 196939, 19],
['sheep', 1573, 1084, 10, 105, 2266, 0]
];
console.log(animals.map(([name, ...data]) => ({name, data})));
alternative if your node version does not support lambdas:
animals.map(function (animal) {
return {
name: animal.shift(),
data: animal
};
});

Related

pass data to data line chart

rates: [
{
id: 1,
idea_id: this.$route.params.id_Idae,
// group_id: "1",
moon: 1,
revenue: 0,
total_revenue: 0,
cost: 0,
total_cost: 0,
profit: 0,
},
],
addDataToChart() {
this.rates.map((item, index) => {
var l = this.rates[index].profit;
this.trazMali.push({
id: l,
});
console.log(l);
console.error(index);
});
},
var x = this.trazMali;
datasets: [
{
label: "# of Votes",
data: x,
borderColor: ["rgba(255, 159, 64, 1)"],
borderWidth: 1,
},
],
i want pass data from a p tag to data of line chart but my codes Maximum call stack size exceeded

How to select random object from JSON file in discord.js

I've done some searching around and I found some posts on here but my code doesn't want to work.
Basically I'm making a discord bot and I want to select an object from a JSON file at random.
This is my command:
const UserData = require('../data/users.js');
const monster = require('../data/monsters.json');
module.exports = {
name: 'battle',
aliases: ['fight'],
cooldown: 0,
description: 'User fights against a monster alone or in group',
execute(client, message, args) {
let enemy = monster[Math.floor(Math.random() * monster.length)]
UserData.findOne({
userID: message.author.id
}, (error, userdata) => {
if (error) console.log(error);
if (!userdata) {
return message.reply(`you don't have an account!`);
} else {
console.log(enemy);
return message.channel.send(`${enemy} spawned!`);
}
})
}
}
And this is my JSON file:
"1" : {
"name": "Blue Slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"2": {
"name": "Red slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"3": {
"name": "Green slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
}
}
If I want put the objects in the command manually and then randomly select them it works and if instead of "monster.length" I put a number then it also works but I still get undefined if it should be 3.
This way I also always get undefined in console log from monster.length.
What am I doing wrong?
Your monsters.json file contains an object and objects don't have lengths. You can however convert it to an array, using Object.values() that returns an array of the given object's own enumerable property values.
Check out the snippet below:
let monsters = {
1: {
name: 'Blue Slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
2: {
name: 'Red slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
3: {
name: 'Green slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
};
function randomObject(obj) {
let arr = Object.values(obj);
return arr[Math.floor(Math.random() * arr.length)];
}
let enemy = randomObject(monsters);
console.log(enemy);

How can i pass multiple values to a function like we do in concat()?

here are two arrays from my code written below .
i have wrote a function to add their elements but i want to make something that can take any number of arrays and join them accordingly!
array 1:
var product =
[ [ 'Product Code' ],
[ 'AFC' ],
[ 'MFC' ],
[ 'AC' ],
[ 'MC' ],
[ 'AT' ],
[ 'MT' ],
[ 'AD' ],
[ 'MTB' ],
[ 'HBB' ] ]
array 2:
var quantity =
[ [ 'S', 'M', 'L', 'XL' ],
[ 16, 17, 6, 0 ],
[ 4, 2, 0, 0 ],
[ 2, 11, 0, 0 ],
[ 2, 6, 2, 0 ],
[ 6, 17, 1, 0 ],
[ 0, 2, 0, 0 ],
[ 0, 1, 0, 0 ],
[ 0, 1, 0, 0 ],
[ 0, 0, 1, 0 ] ]
var final = msJoin(product,qty);
final =
[ [ 'Product Code', 'S', 'M', 'L', 'XL' ],
[ 'AFC', 16, 17, 6, 0 ],
[ 'MFC', 4, 2, 0, 0 ],
[ 'AC', 2, 11, 0, 0 ],
[ 'MC', 2, 6, 2, 0 ],
[ 'AT', 6, 17, 1, 0 ],
[ 'MT', 0, 2, 0, 0 ],
[ 'AD', 0, 1, 0, 0 ],
[ 'MTB', 0, 1, 0, 0 ],
[ 'HBB', 0, 0, 1, 0 ] ]
with the code below:
function msJoin(array1,array2){
var concatArray = (array1,array2)=>{
var final = [];
for(var i = 0 ; i<array1.length;i++){
var tempElement = [];
array1[i].forEach(
function (ee){
tempElement.push(ee);
console.log(ee);
}
);
array2[i].forEach(
function (ee){
tempElement.push(ee);
console.log(ee);
}
);
final.push(tempElement);
}
return final;
}
return concatArray(array1,array2);
}
how can I write it for dynamic numbers of arrays ?
ms(array1,array2,array3..........);
You can simply use reduce and map to get the result you want.
function joinArray(...arr) {
return arr.reduce((a, b) => a.map((e, i) => [...e, ...b[i]]));
}
var product = [
["Product Code"],
["AFC"],
["MFC"],
["AC"],
["MC"],
["AT"],
["MT"],
["AD"],
["MTB"],
["HBB"],
];
var quantity = [
["S", "M", "L", "XL"],
[16, 17, 6, 0],
[4, 2, 0, 0],
[2, 11, 0, 0],
[2, 6, 2, 0],
[6, 17, 1, 0],
[0, 2, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
];
var brand = [
["Sasdf"],
["asdg"],
["223"],
["asdf"],
["gasdf"],
["asdfa"],
["232"],
["gasdf"],
["asdf"],
["323"],
];
const output = joinArray(product, quantity, brand);
console.log(output);
You can use forEach to add elements in a single array from any number of arrays.
You can also use
result[j] = [...result[j], ...val];
var product = [
["Product Code"],
["AFC"],
["MFC"],
["AC"],
["MC"],
["AT"],
["MT"],
["AD"],
["MTB"],
["HBB"],
];
var second = [
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
["temp"],
];
var quantity = [
["S", "M", "L", "XL"],
[16, 17, 6, 0],
[4, 2, 0, 0],
[2, 11, 0, 0],
[2, 6, 2, 0],
[6, 17, 1, 0],
[0, 2, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
];
function join(...arrs) {
const result = Array(arrs[0].length).fill([]);
arrs.forEach((arr, i) => {
arr.forEach((val, j) => {
result[j] = result[j].concat(val);
});
});
return result;
}
console.log(join(product, second, quantity));
function add() {
let a = 0
Object.keys(arguments).forEach(ckey => {
a = a + arguments[ckey]
})
console.log(a)
}
add(1)
add(1, 4, 21, 123, 1)
If you have lodash imported,
import {zip, join} from 'lodash';
const product =
[ [ 'Product Code' ],
[ 'AFC' ],
[ 'MFC' ],
[ 'AC' ],
[ 'MC' ],
[ 'AT' ],
[ 'MT' ],
[ 'AD' ],
[ 'MTB' ],
[ 'HBB' ] ];
const quantity =
[ [ 'S', 'M', 'L', 'XL' ],
[ 16, 17, 6, 0 ],
[ 4, 2, 0, 0 ],
[ 2, 11, 0, 0 ],
[ 2, 6, 2, 0 ],
[ 6, 17, 1, 0 ],
[ 0, 2, 0, 0 ],
[ 0, 1, 0, 0 ],
[ 0, 1, 0, 0 ],
[ 0, 0, 1, 0 ] ];
const result = zip(product, quantity).map(e => [join(e)]);
console.log(result);

Hide and show Google line chart based on checkbox toggle toggle(Check/Uncheck)

I'm trying to make a google line chart with 4 lines in it.
And based on checkbox toggle(Check/Uncheck) I have to Hide and show the chart lines but I got some error.
I am using this fiddle sample
Error screen shot
My code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" >
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawMultilineChart);
function drawMultilineChart(){
var forGraph={
"201": [
[
"date",
"subscribers",
"clicks",
"ctr",
"sent"
],
[
"2020-07-11",
32,
30,
0.347947,
8622
],
[
"2020-07-12",
46,
36,
0.4111,
8757
],
[
"2020-07-13",
37,
43,
0.523624,
8212
],
[
"2020-07-14",
49,
73,
0.69385,
10521
],
[
"2020-07-15",
48,
39,
0.520903,
7487
],
[
"2020-07-16",
37,
34,
0.476658,
7133
],
[
"2020-07-17",
31,
31,
0.355872,
8711
],
[
"2020-07-18",
40,
55,
0.611995,
8987
],
[
"2020-07-19",
42,
32,
0.350301,
9135
],
[
"2020-07-20",
39,
30,
0.42206,
7108
],
[
"2020-07-21",
37,
27,
0.257535,
10484
],
[
"2020-07-22",
46,
38,
0.542392,
7006
],
[
"2020-07-23",
38,
24,
0.360469,
6658
],
[
"2020-07-24",
46,
24,
0.311891,
7695
],
[
"2020-07-25",
43,
35,
0.437883,
7993
],
[
"2020-07-26",
37,
37,
0.454601,
8139
],
[
"2020-07-27",
37,
30,
0.42511,
7057
],
[
"2020-07-28",
26,
50,
0.440956,
11339
],
[
"2020-07-29",
22,
28,
0.338614,
8269
],
[
"2020-07-30",
29,
36,
0.327899,
10979
],
[
"2020-07-31",
28,
29,
0.388427,
7466
],
[
"2020-08-01",
36,
20,
0.230123,
8691
],
[
"2020-08-02",
21,
29,
0.34491,
8408
],
[
"2020-08-03",
40,
36,
0.429748,
8377
],
[
"2020-08-04",
49,
27,
0.359904,
7502
],
[
"2020-08-05",
37,
12,
0.129296,
9281
],
[
"2020-08-06",
33,
24,
0.277425,
8651
],
[
"2020-08-07",
42,
12,
0.142163,
8441
],
[
"2020-08-08",
42,
24,
0.257428,
9323
],
[
"2020-08-09",
34,
32,
0.336559,
9508
],
[
"2020-08-10",
28,
16,
0.296846,
5390
]
],
"200": [
[
"date",
"subscribers",
"clicks",
"ctr",
"sent"
],
[
"2020-07-11",
0,
2,
0.78125,
256
],
[
"2020-07-12",
1,
0,
0,
239
],
[
"2020-07-13",
0,
1,
0.460829,
217
],
[
"2020-07-24",
0,
1,
0.684932,
146
],
[
"2020-07-14",
0,
0,
0,
261
],
[
"2020-07-27",
0,
1,
0.70922,
141
],
[
"2020-07-15",
0,
0,
0,
155
],
[
"2020-07-31",
0,
1,
0.694444,
144
],
[
"2020-07-16",
1,
0,
0,
135
],
[
"2020-08-04",
2,
1,
0.561798,
178
],
[
"2020-07-17",
0,
0,
0,
123
],
[
"2020-08-07",
1,
2,
0.873362,
229
],
[
"2020-07-18",
0,
0,
0,
134
],
[
"2020-08-10",
1,
2,
2.10526,
95
],
[
"2020-07-19",
0,
0,
0,
128
],
[
"2020-07-20",
0,
0,
0,
67
],
[
"2020-07-21",
1,
0,
0,
126
],
[
"2020-07-22",
2,
0,
0,
92
],
[
"2020-07-23",
0,
0,
0,
156
],
[
"2020-07-25",
2,
0,
0,
154
],
[
"2020-07-26",
0,
0,
0,
181
],
[
"2020-07-28",
1,
0,
0,
192
],
[
"2020-07-29",
1,
0,
0,
140
],
[
"2020-07-30",
1,
0,
0,
136
],
[
"2020-08-01",
1,
0,
0,
159
],
[
"2020-08-02",
0,
0,
0,
154
],
[
"2020-08-03",
0,
0,
0,
137
],
[
"2020-08-05",
0,
0,
0,
149
],
[
"2020-08-06",
2,
0,
0,
209
],
[
"2020-08-08",
0,
0,
0,
215
],
[
"2020-08-09",
0,
0,
0,
215
]
]
};
var arrChartItems = [];
var chartDivMultiple = [];
var materialChart = [];
var dataChart = [];
var count = ObjectLength(forGraph);
var propertyName = Object.keys(forGraph);
for (var i = 0; i < count; i++) {
var idCreated=`chart_${i}`;
var idProperty=propertyName[i];
$('.report').prepend(`<h3>${idProperty}</h3><div id="${idCreated}">loading....</div>`);
};
var performanceStatusGraphHeading = Object.keys(forGraph); // only heading if
// data seperation for every chart
var i = 0;
for (var property in forGraph) {
arrChartItems[i] = (forGraph[property]);
i++;
}
var view= [];
var materialChart = [];
for (var i = 0; i < count; i++) {
var chartDivMultiple = [];
dataChart[i] = google.visualization.arrayToDataTable(arrChartItems[i]);
view[i] = new google.visualization.DataView(dataChart[i]);
var seriesColors = ['blue', 'red', 'orange','green'];
chartDivMultiple[i] = document.getElementById('chart_' + i);
materialChart[i] = new google.visualization.LineChart(chartDivMultiple[i]);
var options = {
width: '100%',
height: 300,
colors: seriesColors
};
var arrItems = [];
materialChart[i].draw( view[i], options);
$('#series').find(':checkbox').change(function () {
var cols = [0];
var colors = [];
$('#series').find(':checkbox:checked').each(function () {
console.log(this);
var value = parseInt($(this).attr('value'));
cols.push(value);
colors.push(seriesColors[value - 1]);
console.log(value, 'colors: ', colors);
});
view.setColumns(cols);
materialChart[i].draw(view[i], options);
});
}
function ObjectLength(object) {
var length = 0;
for (var key in object) {
if (object.hasOwnProperty(key)) {
++length;
}
}
return length;
};
}
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2 /css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<ul id="series" style="list-style: none">
<li><input type="checkbox" name="series" value="1" checked="true" />subscribers</li>
<li><input type="checkbox" name="series" value="2" checked="true" />clicks</li>
<li><input type="checkbox" name="series" value="3" checked="true" />ctr</li>
<li><input type="checkbox" name="series" value="4" checked="true" />sent</li>
</ul>
<div class="report"></div>

eCharts how to get xAxis data

I have some code with event on click in echart.js like this
mytempChart2.on('click', function (params)
//params.seriesName return aktif/non aktif
{window.open('' + encodeURIComponent(params.dataType) + '.html', '_self');
});
I read documentation echart on https://www.echartsjs.com/en/tutorial.html#Events%20and%20Actions%20in%20ECharts
but i dont find param to get xAxis data, xAxis data on my chart is date.
Look my picture i want to get this value (red circle)
My full code
// ==============================================================
// Line chart
// ==============================================================
var dom2 = document.getElementById("grafik2");
var mytempChart2 = echarts.init(dom2);
var app = {};
option2 = null;
option2 = {
tooltip : {
trigger: 'axis'
},
legend: {
data:['Non-Aktif', 'Aktif Kembali']
},
toolbox: {
show : true,
feature : {
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
color: ["#EF5350", "#2FBF2F"],
calculable : true,
xAxis : [
{
type : 'category',
boundaryGap : false,
data : [01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,],
}
],
yAxis : [
{
type : 'value',
axisLabel : {
formatter: '{value}'
}
}
],
series : [
{
name:'Non-Aktif',
type:'line',
data:[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],
markPoint : {
data : [
{name: 'tanggal', value: 100},
{type : 'max', name: 'Tertinggi'},
{type : 'min', name: 'Terendah'}
]
},
itemStyle: {
normal: {
lineStyle: {
shadowColor : 'rgba(0,0,0,0.3)',
shadowBlur: 10,
shadowOffsetX: 8,
shadowOffsetY: 8
}
}
},
markLine : {
data : [
{type : 'average', name : 'Rata-rata'}
]
}
},
{
name:'Aktif Kembali',
type:'line',
data:[0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],
markPoint : {
data : [
{type : 'max', name: 'Tertinggi'},
{type : 'min', name: 'Terendah'}
]
},
itemStyle: {
normal: {
lineStyle: {
shadowColor : 'rgba(0,0,0,0.3)',
shadowBlur: 10,
shadowOffsetX: 8,
shadowOffsetY: 8
}
}
},
markLine : {
data : [
{type : 'average', name : 'Rata-rata'}
]
}
}
]
};
if (option2 && typeof option2 === "object") {
mytempChart2.setOption(option2, true), $(function() {
function resize() {
setTimeout(function() {
mytempChart2.resize()
}, 100)
}
$(window).on("resize", resize), $(".sidebartoggler").on("click", resize)
});
}
mytempChart2.setOption(option2);
mytempChart2.on('click', function (params)
//params.seriesName return aktif/non aktif
{window.open('' + encodeURIComponent(params.name) + '.html', '_self');
});
You can use the params object as specified by you. you need to access the name property which holds the value on x axis.
Please find the working code below:
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
option = {
xAxis: [{
type: 'category',
boundaryGap: false,
data: [01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ],
}],
yAxis: [{
type: 'value',
axisLabel: {
formatter: '{value}'
}
}],
series: [{
name: 'Non-Aktif',
type: 'line',
data: [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
markPoint: {
data: [{
name: 'tanggal',
value: 100
},
{
type: 'max',
name: 'Tertinggi'
},
{
type: 'min',
name: 'Terendah'
}
]
},
itemStyle: {
normal: {
lineStyle: {
shadowColor: 'rgba(0,0,0,0.3)',
shadowBlur: 10,
shadowOffsetX: 8,
shadowOffsetY: 8
}
}
},
markLine: {
data: [{
type: 'average',
name: 'Rata-rata'
}]
}
},
{
name: 'Aktif Kembali',
type: 'line',
data: [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],
markPoint: {
data: [{
type: 'max',
name: 'Tertinggi'
},
{
type: 'min',
name: 'Terendah'
}
]
},
itemStyle: {
normal: {
lineStyle: {
shadowColor: 'rgba(0,0,0,0.3)',
shadowBlur: 10,
shadowOffsetX: 8,
shadowOffsetY: 8
}
}
},
markLine: {
data: [{
type: 'average',
name: 'Rata-rata'
}]
}
}
]
}
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
myChart.on('click', function(params) {
console.log(params.name);
});
<div id="main" style="width: 600px;height:400px;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.6.0/echarts.min.js"></script>

Categories