Array javascript output - javascript

How to recover the elements of a foreach for reformed in this way:
['julie','nicola','sahra']
My code
var outPutStats = ''
client.data.forEach(function(element) {
outPutStats += [element.name];
});
.............................
.............................
xAxis: {
name: [outPutStats] // Must be ['dataName1','dataName2']
},
yAxis: {
title: {
text: null
}
},

try this:
var outputStats = [];
client.data.forEach(function(element) {
outputStats.push(element.name);
});
It's probably more semantically accurate to use Array#map instead, though, if the clients you want support it (which afaik they should if they support forEach):
var outputStats = client.data.map(function(element) { return element.name; });

If you want to copy client.data into a new array outPutStats then this will work (although I don't see the reason why, you could just use client.data):
// This must be an array
var outPutStats = [];
client.data.forEach(function(element) {
// fill the array with elements
outPutStats.push(element.name);
});
// ...
// ...
xAxis: {
name: outPutStats // outPutStats is already an array
},
yAxis: {
title: {
text: null
}
},

Related

MongoDB if statement in a parameter

I am trying to not make my code redundant and I would like to know, if in a .updateOne method, when Im passing data to change, if its possible to implement if statement to choose from the data. Here is a situation.
I have my db model:
const depositarySchema = new Schema({
euid: {
type: String,
required: true
},
euid2: {
type: String
},
count: {
type: Number,
required: true
},
euroPallets: {
type: Number,
},
biggerPallets: {
type: Number,
},
otherPallets: {
type: Number,
},
depositary: {
type: Number,
required: true
},
title: {
type: String
}
});
Then I have a variable: var = 1 for euroPallets, 2 for biggerPallets and 3 for otherPallets. I would like to implement something like this:
Depositary.updateOne(
{
euid: euid,
},
{
count: dep.count - palletCounter,
if(var === 1){
euroPallets: count}
elseif(var===2){
biggerPallets: count}
else{
otherPallets: count}
},
where count is just a number. I hope its understandable what im trying to achieve, sorry for a wrong syntax.
Wernfried Domscheit beat me to it, but I will post my answer anyways.
const palletTypes = ['otherPallets', 'euroPallets', 'biggerPallets'];
var count = ep.count - palletCounter;
var palletType = palletTypes[count] || palletTypes[0];
var pallets = {'count': count};
pallets[palletType] = count;
Depositary.updateOne(
{euid: euid},
pallets
)
I would honestly just make a helper method so you can just send in parameters and it will turn everything to the correct objects.
updatePallets(euid, ep.count, palletCounter)
Maybe this one:
let upd = {
euid: euid,
count: dep.count - palletCounter
};
if (var === 1) {
upd['euroPallets'] = count;
}
else if (var === 2) {
upd['biggerPallets'] = count;
}
else {
upd['otherPallets'] = count;
}
Depositary.updateOne(upd)
EDIT:
For .updateOne() method to actually work like I want to, you need to separate the euid parameter. The correct solution is this:
let upd = {
count: dep.count - palletCounter
};
if (var === 1) {
upd['euroPallets'] = count;
}
else if (var === 2) {
upd['biggerPallets'] = count;
}
else {
upd['otherPallets'] = count;
}
Depositary.updateOne(
{
euid: euid,
},
upd,
)

Updating in chart.js

I'm trying to figure out how to update a chart.js chart. Google's returned with a lot of answers and I think some are outdated because I can't seem to get any of the solutions to work. The documentation page says just use chartname.update() but it doesn't seem to work for me. I already checked console to make sure the chart object was updating. For some reason the chart itself on the page just isn't changing.
let chartContainer = document.getElementById('charts');
let overview = {
create: function () {
let chartCanvas = document.createElement('canvas');
chartCanvas.id = 'overviewChart';
chartCanvas.appendChild(document.createTextNode('test'));
chartContainer.appendChild(chartCanvas);
let overviewChart = document.getElementById('overviewChart').getContext('2d');
renderChart = new Chart(overviewChart, {
type: 'bar',
data: {
labels:subjectList,
datasets: [{
barThickness: 'flex',
label: 'Completed Credits',
data: []
}]
},
options: {
}
})
},
reload: function() {
console.log('reloaded overview chart');
renderChart.data.datasets.data = [];
for (subject in classes) {
console.log('adding: ' + classes[subject].count)
renderChart.data.datasets.data.push(classes[subject].count);
}
renderChart.update();
}
}
function reloadCharts() {
overview.reload();
}
overview.create();
There are problems in your reload function where you access renderChart.data.datasets.
Please note that renderChart.data.datasets is an array. Therefore, you need to make the following changes:
reload: function() {
// renderChart.data.datasets.data = []; // old
renderChart.data.datasets[0].data = []; // new
for (subject in classes) {
console.log('adding: ' + classes[subject].count)
// renderChart.data.datasets.data.push(classes[subject].count); // old
renderChart.data.datasets[0].data.push(classes[subject].count); // new
}
renderChart.update();
}

How do i use the json data fetched by fetch()

I used the following code to fetch JSON data which was a success. I initialized a global array and stored one unit of that data in an array. Now somewhere in my code, there is an array nested inside an object how do I pass this array there?
var myRequest = new Request("https://script.googleusercontent.com/macros/echo?user_content_key=KW75vuIX25SoStm_K2HLVQNBRF2fx_5URDdL-vYJfUSTBaOAlMkJeWc25wjo5zdMLaznziyuqNd4B5kNs8k3tH0OxgnfssPwm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnIFtsXaNuh0rFflir-T-GWuA8AvQ2kUI-jEwpZssg8RaEHh5W9MAfgDGMRkNsN06wEWY2nZ7HPw5&lib=M_p61mp1Qy6uGkXTBzlj4kloBXIZCdEN3")
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++)
{
arr[i]=data.user[i].battingScore;
}
return arr;
});
This is where I want to use the arr:
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
title: {
text: 'Logarithmic axis demo'
},
xAxis: {
tickInterval: 1,
type: 'logarithmic'
},
yAxis: {
type: 'logarithmic',
minorTickInterval: 0.1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br />',
pointFormat: 'x = {point.x}, y = {point.y}'
},
series: [{
data:[], //here
pointStart: 1
}]
});
});
});
Note: Here, series is an array of objects but is an attribute of hello object. I want the values of arr inside data which is an array. How to do that?
If you want to gather the data before rendering the chart, you could do this.
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
arr[i]=data.user[i].battingScore;
}
return arr;
})
.then(function(scores){
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
. . .
series: [{
data:scores,
pointStart: 1
}]
});
});
});
});
Otherwise, you can define your myChart3 as a global variable and change "var myChart3=" to just "myChart3=" in your event listener. Then, you can populate the data into the existing chart using series.addPoint like this:
var myChart3;
document.addEventListener('DOMContentLoaded', function () {
myChart3 = Highcharts.chart('c', {
. . .
});
});
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
myChart3.series[0].addPoint(data.user[i].battingScore, false);
}
myChart3.redraw();
},
cache: false
});

how to edit javascript Objects with loop (Jvectormap)

I'm new to Javascript objects and Jquery and I have no clue how I do something like this:
series: {
regions: [{
values: {
for(i = 0; i < 10; i++){
[countryname[i]] : countrycolor[i]
}
[countrynames] : countrycolor,
}
}]
}
How do I make the for loop basically print out the country names and countrycolors that I have in an array.
Im using jvectormap and the full code which im using right now for the map is:
var countrynames = "<?php if (isset($countryname)) {echo $countryname;}; ?>";
var countrycolor = "<?php if (isset($countrycolor)) {echo $countrycolor;}; ?>";
$('#world-map').vectorMap({
map: 'world_mill',
onRegionClick: function (event, code) {
window.location.href = "country.php?id=" + code;
},
series: {
regions: [{
values: {
[countrynames] : countrycolor,
}
}]
}
});
You could use reduce[1] function to achive what you want on plain javascript
{
values: countrynames.reduce(function(result, country, index) {
result[country] = countrycolor[index];
return result;
}, {});
}
[1] - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

javascript: Alter the output of a function to the specified decimal place

I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using fin-hypergrid.
There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:
aggregates = {Value: rollups.sum(11)}
I would like to change this value to return 2 decimal places and tried:
rollups.sum(11).toFixed(2)
However, it gives the error : "rollups.sum(...).toFixed is not a function"
If I try something like:
parseFloat(rollups.sum(11)).toFixed(2)
it throws the error: "can't assign to properties of (new String("NaN")): not an object"
so it has to be a function object.
May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?
(side info: rollups.sum(11) comes from a module which gives:
sum: function(columnIndex) {
return sum.bind(this, columnIndex);
}
)
Sorry I could not post sample output here due to data confidentiality issues.
However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".
window.onload = function() {
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [{
label: 'Grouping',
ctrls: [
{ name: 'treeview', checked: false, setter: toggleTreeview },
{ name: 'aggregates', checked: false, setter: toggleAggregates },
{ name: 'grouping', checked: false, setter: toggleGrouping}
]
}
];
function derivedPeopleSchema(columns) {
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' });
var columnSchema = factory.lookup('last_name');
if (columnSchema) {
columnSchema.defaultOp = 'IN';
}
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
}
var customSchema = [
{ name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true },
{ name: 'total_number_of_pets_owned', type: 'number' },
{ name: 'height', type: 'number' },
'birthDate',
'birthState',
'employed',
{ name: 'income', type: 'number' },
{ name: 'travel', type: 'number' }
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions = {
data: people1,
schema: peopleSchema,
margin: { bottom: '17px' }
},
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options) {
options = options || {};
if (data === people1 || data === people2) {
options.schema = peopleSchema;
}
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
}
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions({
//container: document.getElementById('dialog-container'),
settings: false
});
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) { // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add({
children: [{
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
}],
type: 'columnFilter'
});
}
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates = {
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
},
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates() {
if (!aggView){
aggView = new AggView(grid, {});
aggView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked) {
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
} else {
grid.setAggregateGroups([], []);
aggViewOn = false;
}
}
function toggleTreeview() {
if (this.checked) {
treeView = new TreeView(grid, { treeColumn: 'State' });
treeView.setPipeline({ includeSorter: true, includeFilter: true });
treeView.setRelation(true, true);
} else {
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
}
}
var groupView, groupViewOn = false;
function toggleGrouping(){
if (!groupView){
groupView = new GroupView(grid, {});
groupView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked){
grid.setGroups(groups);
groupViewOn = true;
} else {
grid.setGroups([]);
groupViewOn = false;
}
}
you may try:
(rollups.sum(11)).toFixed(2)
enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal
edited #2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName) {
if(aggViewOn)
{
if(config.columnName == "total_pets")
{
if(typeof(config.value) == 'number')
{
config.value = config.value.toFixed(2);
}
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
{
config.value = config.value[1].toFixed(2);
}
}
}
return grid.cellRenderers.get(rendererName);
};

Categories