Node.js db results to chartist.js reformat - node.js

I can hardcode data (labels and series) for a chartist, but need help figuring out how to reformat a db query result.
The app.js contains
const ParmLocation = req.query.ParmLocation
const ParmLine = req.query.ParmLine
console.log("pls2 page requested for " + ParmLocation + " Line " + ParmLine)
// execute a database query
const userToken = db.DBQueryBHBrowser("select PrinterType, count(1) as PCount from printerNames Group by PrinterType");
userToken.then(function(result) {
console.log(JSON.stringify(result.recordset));
res.render('chartpage', {ParmLocation: ParmLocation, ParmLine: ParmLine, S2: result.recordset});
...
The chartpage.js contains below with "data" that works and is in the format needed.
...
var data = {
// A labels array that can contain any sort of values
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// Our series array that contains series data arrays
series: [[5, 2, 4, 2, 0]]
};
var options = { };
// Create charts with data and options
new Chartist.Line('#TargetRate', data, options);
new Chartist.Line('#SecondShift', {{S2}}, options);
Console log of result.recordset:
[
{ PrinterType: 'Dymo400', PCount: 8 },
{ PrinterType: 'Dymo450', PCount: 30 },
{ PrinterType: 'Dymo4XL', PCount: 13 },
{ PrinterType: 'Laser', PCount: 8 },
{ PrinterType: 'Sato', PCount: 2 }
]

This seemed to work for my purposes
result.recordset.forEach(function(row){
labels.push(Object.values(Object.values(row))[0]);
series.push(Object.values(Object.values(row))[1]);
});
const chartdata = { labels: labels, series: series};

Related

using for loop with push() to create arrays within a new array

I'm working on a project where I need to declare customsItem formatted in a particular way.
The format given is:
var customsItem = {
"description":"T-Shirt",
"quantity":20,
"net_weight":"1",
"mass_unit":"lb",
"value_amount":"200",
"value_currency":"USD",
"origin_country":"US",
};
In my project however, I have multiple descriptions, so I need to make customsItem an array containing both.
I have array itemInCart =
[
{
itemDescription: 't-shirt',
qty: 1,
pre_orderQty: 1,
price: 30,
weight: 8
},
{
itemDescription: 'pants',
qty: 0,
pre_orderQty: 1,
price: 40,
weight: 5
}
]
I need to get these items in the correct format and within an array called customsItem. I thought to do this using a for loop with push(). Currently, I'm not getting anything when I try to console.log(customsItem), so I'm not sure if this is the best way to achieve the results that I am trying to get. I would really appreciate any help or advice on how to correctly get the results that I need. Thank you!
const customsItem = [];
for (var item of itemInCart) {
const items = {
"description":item.itemDescription,
"quantity":item.qty + item.pre_orderQty,
"net_weight":item.weight,
"mass_unit":"oz",
"value_amount":item.price,
"value_currency":"USD",
"origin_country":"US",
}
customItem.push(
items
)
}
You are not pushing into the correct array:
const customsItem = [];
for (var item of itemInCart) {
const items = {
"description":item.itemDescription,
"quantity":item.qty + item.pre_orderQty,
"net_weight":item.weight,
"mass_unit":"oz",
"value_amount":item.price,
"value_currency":"USD",
"origin_country":"US",
}
customItem.push( <---- needs to be customsItem.push
items
)
}

Issue while merging multiple JSON Objects

I'm trying to auto-generate a JSON object for creating a dynamic interactive list message that will be sent to users on WhatsApp.
I need a JSON object in following format:
"sections": [
{
"title": "Main Title",
"rows": [
{
"title": "row 1 title",
},
{
"title": "row 2 title",
}
]
}
]
The above code will generate a list like this
But I don't want to hard code the row's title part {"title": "row 1 title",},{"title": "row 2 title", } .
I tried using the below method where I fetch the title value from an array and merge it using spread syntax but it only returns undefined and doesn't combine all the objects.
method.js
async function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
let data1, data2, d = {}
let i = 0
while (i < arr.length) {
data1 = JSON.parse(`{"title": "${arr[i]}"}`)
data2 = JSON.parse(`{"title": "${arr[i + 1]}"}`)
i++
d = { ...data1, ...data2 }
}
console.log(d)
catch (e) {
console.log(e)
}
}
genJSON()
OUTPUT:
Interactive List message: https://developers.facebook.com/docs/whatsapp/guides/interactive-messages/
How can I achieve the following output {"title": "row 1",},{"title": "row 2", ..} ? Any help or advice is appreciated.
There were two issues with your code:
You were trying to merge two dictionaries with the same keys, hence the previous key gets overwritten. Instead, you should use a JSON Array and append to it.
data2 will be undefined when i = arr.length - 1
I've fixed both the errors in the below code snippet
function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
try {
let d = []
for (const row of arr) {
d.push({
title: row
})
}
console.log(d)
} catch (e) {
console.log(e)
}
}
genJSON()

how can I update the Line chart values from API Response in react native

My API respond seven days moisture record, now i want to extract the seven days name and moisture values. my Api response is in JSON so I use for loop to extract the days and moisture values, now problem is that when by using useState I set the moisture and days values ,and write days and moisture in line chart data it show NAN in place of days and moisturereading. please help to solve this problem. this is my first work in React Native so please correct me if i am wrong at any line of code.
this is My Code
`
const [days, setdays] = useState([])
const [moisturereading, setMoistureReading] = useState([])
useEffect(()=>{
//deviceinfo()
callapi()
})
function callapi() {
fetch('http://192.168.8.1/mobile/DeviceDataStats?deviceid=1' )
.then(data=>data.json())
.then(data2=>{
console.log(data2)
//listday[]
//listmoisture[]
for(var i=0;i<7;i++)
{
setdays([...days,(data2.Table[i].DayName).slice(0, 3)])
setMoistureReading([...level,(data2.Table[i].Moisturevalue)])
//level.push(data2.Table[i].Moisturevalue)
//days.push((data2.Table[i].DayName).slice(0, 3))
//console.log(data2.Table[i].DayName)
}
})
.catch(err => { console.log(err) })
}
**This is the Line Chart data**
const data = {
labels: ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"], //{days} i want to update labels with days
datasets: [
{
data:[29, 45, 28, 80, 91, 43,55],//{moisturereading} want to update data with moisturereading
color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`, // optional
strokeWidth: 2 // optional
}
],
legend: ["Moisture Values"] // optional
}`
First init first data
const [chartData,setChartData] = React.useState({
labels: [],
datasets: [
{
data:[],
color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`,
strokeWidth: 2
}
],
legend: ["Moisture Values"]
})
then call data function
function callapi() {
fetch('http://192.168.8.1/mobile/DeviceDataStats?deviceid=1' )
.then(r=>r.json())
.then(r=>{
//get 7 elements from array response,
const sevens = r.Table.slice(0,7);
// and return new array contain days
const days = sevens.map(c=>c.DayName.slice(0, 3))
//and return new array contain values
const values = sevens.map(c=>c.Moisturevalue)
//set data to state by extract old object
setChartData({
...chartData,
labels: days,
datasets:[
{
...chartData.datasets[0],
data: values
}
]
})
})
.catch(err => { console.log(err) })
}
final set data to chart
<LineChart
data={chartData}
/>
call callapi() each time you want to refresh data

Datatables.net: Set column width when exporting to XLSX

i have datatables table and i want export content of this table.
Because some headers are so long, i must set specific text of headers. All works fine, but columns with customized text are still so long.
customize: function( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
// Exported excel custom properties
$('row:first c', sheet).attr( 's', '7' );
$('c[r=B1] t', sheet).text( 'Date' ).;
$('c[r=C1] t', sheet).text( 'Type' );
$('c[r=E1] t', sheet).text( 'Subject' );
}
}]
Pls, is possibe set specific width for columns with "new" - shorter texts?
Thanks for any answers.
"customize": function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row:first c', sheet).attr( 's', '2' );
$('row:first c is t', sheet).each(function () {
if (this.innerHTML == 'creationdate') { this.innerHTML = 'Date' }
if (this.innerHTML == 'ty') { this.innerHTML = 'Type' }
if (this.innerHTML == 'sub') { this.innerHTML = 'Subject' }
});
}
Use the customize tag inside the excel button to configure the width options
{
title: "",
exportOptions: { ... }
customize: function (xlsx: any) {
var sheet = xlsx.xl.worksheets["sheet1.xml"];
var col = $("col", sheet);
var col = $('col', sheet);
col.each(function () { //update all columns with width 30
$(this).attr('width', 30);
});
$(col[0]).attr("width", 7); // update specific columns
$(col[4]).attr("width", 7); // update specific columns
}
}

Grouping a IEnumerable<IEnumerable<int>>

I have an object diceRolls that is a IEnumerable>. A data set looks like
{{ 1 , 1 },
{ 1 , 2 },
{ 1 , 3 },
{ 1 , 4 },
{ 1 , 2}}
I need to get a result set that groups the common sets and sums up the total number of rows of that set.
I tried the GroupBy method like this:
var aggregate = sorted.GroupBy(rolls => rolls, rolls => rolls);
But it did not group anything and I could find no fields inside of the rolls object to group by so my only choice was the whole object itself. How do I do this?
You can pass to GroupBy custom IEqualityComparer which implements sequence equals so group by will threat {1, 2} and {1, 2} as the same. But if you know, that your rolls has only 2 elements when you can use anonymous type and its equals implementation:
var sorted = new[] { new[] { 1, 2 }, new[] { 1, 2 }, new[] { 1, 3 }, new[] { 2, 2 } };
var grouped = sorted.GroupBy(roll => new { r0 = roll[0], r1 = roll[1] });
var backToArrays = grouped.Select(g => new[] { g.Key.r0, g.Key.r1 });
This code will produce {{ 1, 2 }, { 1, 3 }, { 2, 2 }}. Is it that you need?

Resources