d3.json was working fine till I included this for loop in it. I am populating the patientList object which is basically a list of patient names, where each patient would have an array of appointment dates and alpha beta values. The database stores multiple rows for each patient where the name and alpha beta values remain same but dates vary. Therefore, this for loop is to sort out the info with name as primary key.But I have no idea what's wrong in here as it's my first time working with d3 and js.
var data;
var patientList = {};
d3.json("data.php", function(error, json) {
if (error) return console.warn(error);
data = json;
for(var i = 0; i < data.length; i++) {
var name = data[i].name;
if(!patientList[name]) {
var newPatient = {
dates: data[i].date,
alpha: data[i].alpha,
beta; data[i].beta
};
patientList[name] = newPatient;
} else {
patientList[name].dates.push(data[i].date);
}
}
alert("Hello," + data[3].name);
});
Any suggestions ??
Thanks in advance!
Maybe it's just the typo in
beta; data[i].beta
which should be
beta: data[i].beta
What does the console.log say?
Related
I made files with table. On those table there is some datas that are changing according to each files. So I created a file where there is a table that sum all of the others tables that are in others files.
First i made my code that sum tables of two files :
function juneFunction() {
var sheet_origin1=SpreadsheetApp
.openById("ID1")
.getSheetByName("Calcul/Machine");
var sheet_origin2=SpreadsheetApp
.openById("ID2")
.getSheetByName("Calcul/Machine");
var sheet_destination=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//define range as a string in A1 notation
var range1="BU4:CF71"
var values1=sheet_origin1.getRange(range1).getValues();
var values2=sheet_origin2.getRange(range1).getValues();
var destinationrange=sheet_destination.getRange("C3:N70");
//Here you sum the values of equivalent cells from different sheets
for(var i=0; i<values1.length;i++)
{
for(var j=0; j<values1[0].length;j++)
{
sum=values1[i][j]+values2[i][j];
destinationrange.getCell(i+1,j+1).setValue(sum);
}
}
}
This code is working perfectly.
But my goal is to sum 26 tables of 26 files.
So I tried to do it with 3 files, here is the code :
function juneFunction() {
var sheet_origin1=SpreadsheetApp
.openById("ID1")
.getSheetByName("Calcul/Machine");
var sheet_origin2=SpreadsheetApp
.openById("ID2")
.getSheetByName("Calcul/Machine");
var sheet_origin3=SpreadsheetApp
.openById("ID3")
.getSheetByName("Calcul/Machine");
var sheet_destination=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//define range as a string in A1 notation
var range1="BU4:CF71"
var values1=sheet_origin1.getRange(range1).getValues();
var values2=sheet_origin2.getRange(range1).getValues();
var values3=sheet_origin3.getRange(range1).getValues();
var destinationrange=sheet_destination.getRange("C3:N70");
//Here you sum the values of equivalent cells from different sheets
for(var i=0; i<values1.length;i++)
{
for(var j=0; j<values1[0].length;j++)
{
for(var k=0; k<values1[0].length;k++){
sum=values1[i][j][k]+values2[i][j][k]+values3[i][j][k];
destinationrange.getCell[[i+1,j+1,k+1]].setValues(sum);
}
}
}
}
Here I have this error : TypeError : Cannot read properly 'setValues' of undefined. This error happen here :
destinationrange.getCell[[i+1,j+1,k+1]].setValues(sum);
I think that the error is coming from the .getCell but i dont know why ...
Range.getCell() takes two arguments: the row offset and the column offset. You are handing it just one argument: an array of three numbers.
You should not be using Range.getCell() in the first place. Instead, use Array.map() to get the sheets, Array.forEach() to iterate over them, and finally Range.setValues() to write all results in one go, like this:
function sumRangeAcrossManySpreadsheets() {
const spreadSheetIds = ['id1', 'id2', 'id3',];
const sheetName = 'Calcul/Machine';
const rangeA1 = 'BU4:CF71';
const targetRange = SpreadsheetApp.getActiveSheet().getRange('C3');
const sheets = spreadSheetIds.map(id => SpreadsheetApp.openById(id).getSheetByName(sheetName));
const result = [];
sheets.forEach((sheet, sheetIndex) => {
if (!sheet) {
throw new Error(`There is no sheet ${sheetName} in spreadsheet ID '${spreadSheetIds[sheetIndex]}'.`);
}
const values = sheet.getRange(rangeA1).getValues();
values.forEach((row, rowIndex) => row.forEach((value, columnIndex) => {
if (!result[rowIndex]) {
result[rowIndex] = new Array(row.length).fill(0);
}
result[rowIndex][columnIndex] += Number(value) || 0;
}));
});
targetRange.offset(0, 0, result.length, result[0].length).setValues(result);
}
I have an array of data like so:
var data = [
["Acid", 0.741593940836, 0.45657115],
["Cannabis", 0.94183423, 0.31475],
["LSD", 0.1367547, 0.936115]
];
Which plots points to a scatterplot.
I also have other arrays of data that look like this - the arrays are declared with the same names of each sub array in data. These arrays are then stored in an array:
var Acid = ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"];
var collection = [Acid, Cannabis, LSD];
I'm trying to create some code returns one (two or all) of the arrays (Acid, Cannabis, LSD) based on a selection of the points in the scatterplot. The code I have so far is as below - it should be noted that the selecting points is done via Lasso, I've included that code also.
var lasso_end = function() {
lasso.items()
.classed("not_possible",false)
.classed("possible",false);
var selected = lasso.selectedItems()
.classed("selected", true)
.attr("r", 13);
var selectedPoints = [];
selected.data().forEach((arr) => {
arr.forEach((d) => {
selectedPoints.push(d);
});
});
for(var i = 0; i < selectedPoints.length; i++) {
for(var j = 0; j < collection.length; j++) {
if(selectedPoints[0] == collection[j]) {
console.log(collection[j]);
}
}
}
Just to reiterate, I'm trying log data from Arrays Acid, Cannabis, and LSD to the console, if points in the array data is selected
In response to one of the comments, I've put a console.log() after selectedPoints and this is the output and format:
Ok, so if I understand correctly, after doing
selected.data().forEach((arr) => {
arr.forEach((d) => {
selectedPoints.push(d);
});
});
your selectedPoints array logs out as
"Acid",
0.123123,
0.123131,
"Cannabis"
0.232222,
0.221121... etc.
and then you want to console.log the arrays whose names are in the above output, here the arrays Acid and Cannabis.
The issue is that you create the array collection with named variables holding the word arrays: the names of the variables that held the arrays don't transfer, you can't do
var foo = 2
var array = [foo]
and the try to access the value with array[foo], that's not how JS arrays work. They only have numerical indices.
You should use an object:
var collection = {
Acid: ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"]
}
and then extraxt the names from selectedPoints
var pointNames = selectedPoints.filter(x => typeof x === "string")
and the loop through the pointNames array, logging out the corresponding property on the object collection if it exists. Here's a simplified snippet:
var data = [
["Acid", 0.741593940836, 0.45657115],
["Cannabis", 0.94183423, 0.31475],
["LSD", 0.1367547, 0.936115]
];
var selectedPoints = ['Acid', 0.741593940836, 0.45657115];
var collection = {
Acid: ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"]
}
var pointNames = selectedPoints.filter(x => typeof x === "string")
pointNames.forEach(point => {
if(collection[point]) {
console.log(collection[point])
}
})
I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.
I have two arrays called one and two. one contains string values and two int values.
I'm trying:
var messageObject = { 'One': one,
'Two': two};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
I'm getting "Undefined", though the array is populated.
They are receiving data from a database, like this:
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM aluno', [], function(transaction, results) {
len = results.rows.length, i;
for (i = 0; i < results.rows.length; i++) {
one[i] = results.rows.item(i).fieldOne;
two[i] = results.rows.item(i).fieldTwo;
}
}, null);
});
See the code:
http://jsfiddle.net/U4C6r/2/
Edited Answer:
The problem seems to be with the DB-Query-Code. Either the query or the callback get never executed, see: http://jsfiddle.net/U4C6r/11/
Original Answer:
var messageObject = {
'One': one,
'Two': two
};
If you define your keys as strings, you should access them as such:
console.log(json['One']);
If you'd like to have them as properties on the object, you should do:
var messageObject = {
One: one,
Two: two
};
Then you could access the data in a chaining fashion, like you want to:
console.log(json.One);
You should also see the difference here and in your IDE
by the specific Syntax-Highlighting - see it? :)
EDIT to updated:
put breakpoint as you read the values from webSQL and check the structure of object you get within loop inspect this obj results.rows.item(i)
Also change your script to this. I am assuming you have global var one = []; and var two = []; declared.
var dynamicArrayContainer = { one : [],
two : []};
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM table', [], function(transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
dynamicArrayContainer .one.push(results.rows.item(i).fieldOne);
dynamicArrayContainer .two.push( results.rows.item(i).fieldTwo);
}
}, null);
});
Try this, put your values directly, as debug exercise
var serializedJSON = JSON.stringify(dynamicArrayContainer);
var json = JSON.parse(serializedJSON);
alert(json.one);
Try this:
var messageObject = { One: 'one',
Two: 'two'};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
Good luck
:)
Update: Enquirer edited the query after this reply was posted. This reply pertains to the original query (ie the first part of the current query)
Here are my codes:
app.get('/index/:name',function(req, res){
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
return veri;
});
console.log(data);
res.render('index', {
title: req.params.name,
para: data
});
});
When i call localhost:8080/index/example it returns [object Object]
I want to print data of array, how can i do this?
I can do it when I'm using php with print_r() function..
Meantime, array's data:
Id Name
1 yab
2 sad
I think OP just want to print the data for debugging purposes, for that you can use the following cross-browser way that uses JSON to print a nice representation of the data:
console.log( JSON.stringify(data, null, 4) );
Something like this should work:
for (var colName in data) {
console.log("column " + colName);
var rows = data[colName];
for (var i = 0; i < rows.length; i++) {
console.log(rows[i]);
}
}
You will have to tweak it for your needs, that's the general way to iterate such objects.
You need to iterate the result collection and print the attributes
$.each(resultArray, function() {
this.id;//use this to write id
this.name;//use this to write name
});
To output to the console you could do something like:
for(var index in data) {
var item = data[index];
var output = [];
for(var field in item) {
output.push(item[field]);
}
console.log(output.join("\t"));
}
For outputting in html, you'd do something like similar, but creating actual HTML nodes. Maybe, something like:
var output = ["<table>"];
for(var index in data) {
output.push("<tr>");
var item = data[index];
for(var field in item) {
output.push("<td>");
output.push(item[field]);
output.push("</td>");
}
output.push("</tr>");
console.log(output.join("\t"));
}
output.push("</table>");
element.innerHTML = output.join("");
I've not tried that in a browser, so there might be a couple of mistakes, but that should do it.
Let me know if you'd like any more help.