Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In Javascript SQLite, is there a better way we can execute a SELECT statement with WHERE IN clause? Let's take the following query as an example:
var ids = [1, 5, 10];
function getBranches (ids) {
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM Branch WHERE id in ?', [ids], function(tx,results){
// process results
});
});
}
I know we can always format the WHERE IN clause for the ids in a way SQL recognizes it as shown below. But I was wondering if there's a nice way to achieve that requirement.
function getBranches (ids) {
db.transaction(function(tx) {
var idClause = ' id in (\"' + ids.join("\",\"") + '\");';
tx.executeSql('SELECT * FROM Branch WHERE ' + idClause, [], function(tx,results){
// process results
});
});
}
Solution 1:
One way is to do without the placeholder ?:
'SELECT * FROM test WHERE col1 in (' + ids.join(',') + ')', [],...
Solution 2:
Another way is to do the fancy prepared statement style as in your example, where you need to put exact number of ? that equals the number of arguments.
var ids = [1, 5, 10];
var placeHolders = new Array(ids.length).fill('?').join(',');
var query = 'SELECT * FROM Branch WHERE id in ('+ placeHolders + ')';
tx.executeSql(query, [ids], ...
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
// I wanted to create a variable to hold the month and a variable that hold the number...
var finances = [
['Jan-1999', 867886],
['Feb-1999', 984653],
['Mar-1999', 322012],
['Apr-1999', -69417],
['May-1999', 310503],
['Jun-1999', 522857],
['Jul-1999', 1033096],
['Aug-1999', 604885],
['Sep-1999', -216386],
['Oct-1999', 477532],
['Nov-1999', 893810]];
What you need is map() that returns a new array with the result of a function applied to your initial array. In this case your functions would either select the first element of the subarray (the date), or the second element (the number).
var finances = [
['Jan-1999', 867886],
['Feb-1999', 984653],
['Mar-1999', 322012],
['Apr-1999', -69417],
['May-1999', 310503],
['Jun-1999', 522857],
['Jul-1999', 1033096],
['Aug-1999', 604885],
['Sep-1999', -216386],
['Oct-1999', 477532],
['Nov-1999', 893810]];
const dates = finances.map((e) => e[0]);
const numbers = finances.map((e) => e[1]);
console.log(dates);
console.log(numbers);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In trying to learn more about JavaScript (Google Apps Script flavor), I created an object structure that I think might be useful for a number of projects. My main goals for this little demonstration are:
learn the use objects (classes) and inheritance
minimize calls to the Spreadsheet Service by summoning a data table once per sheet
use the Named Ranges on the spreadsheet to access the data in the table
The code below seems successful, but surely can be improved. A couple of major questions are:
Is there a better way to accomplish the inheritance of methods and properties than this?
The Spreadsheet() function gets run for each of the Sheet objects, resulting in the environment structure having separate "ss" and "namedRangeList" properties in each of the Sheet objects. Is this normal and expected? Or is there a better approach to avoid this duplication? Or, is JavaScript just recording pointers to a single instance of these objects, so it really doesn't matter that they appear to be duplicated?
Because they are common to and the same for all of the Sheets, I had expected "ss" and "namedRangeList" to show up only at the Environment level and therefore available to the Sheets through inheritance rather than duplication.
What other changes or approaches would improve my fledgling use and understanding of classes and objects?
Here is a stripped down version of my code that preserves the essence of the structure but leaves out comments, error handling, and other functionality.
function Environment() {
this.title = 'Car & Driver';
this.ui = SpreadsheetApp.getUi();
this.dd = new Drivers();
this.cc = new Cars();
}
function Spreadsheet() {
this.ss = SpreadsheetApp.getActiveSpreadsheet();
this.namedRangeList = {};
var namedRanges = this.ss.getNamedRanges();
for (var i = 0; i < namedRanges.length; i++) {
var range = namedRanges[i].getRange();
this.namedRangeList[namedRanges[i].getName()] = {
sheet: range.getSheet().getSheetName(),
row: range.getRow(),
column: range.getColumn(),
rowCount: range.getNumRows(),
columnCount: range.getNumColumns(),
}
}
}
Spreadsheet.prototype = Object.create(Environment.prototype);
function Sheet() {
Spreadsheet.call(this);
this.sheet = this.ss.getSheetByName(this.sheetName);
this.data = this.sheet.getDataRange().getValues();
}
Sheet.prototype = Object.create(Spreadsheet.prototype);
function Cars() {
this.sheetName = 'Cars';
this.abbreviation = 'cc';
Sheet.call(this);
}
Cars.prototype = Object.create(Sheet.prototype);
function Drivers() {
this.sheetName = 'Drivers';
this.abbreviation = 'dd';
Sheet.call(this);
}
Drivers.prototype = Object.create(Sheet.prototype);
Sheet.prototype.idxOf = function(namedRange) {
return (this.namedRangeList[namedRange].rowCount == 1) ?
this.namedRangeList[namedRange].row - 1 :
this.namedRangeList[namedRange].column - 1;
}
function test_Environment() {
var env = new Environment();
env.ui.alert('The third driver is ' +
env.dd.data[3][env.dd.idxOf('ddFirst')] + ' ' + env.dd.data[3][env.dd.idxOf('ddLast')] + '.');
var tests = [
['dd', 2, 'ddLast' , 'Bailey' ],
['dd', 3, 'ddLicense' , 'pro' ],
['cc', 1, 'ccRadio' , 122.5 ],
['cc', 4, 'ccModel' , 'Corvette'],
];
tests.forEach(function(t) {
var v = env[t[0]].data[t[1]][env[t[0]].idxOf(t[2])];
Logger.log( (v == t[3]) + ': ' + (t[0] == 'dd' ? 'Driver ' : 'Car ') +
t[1] + ' ' + t[2].slice(2) + ' is ' + v );
});
env.ui.alert(env.title + ' is all done');
}
You can take a look at the mozilla page of JavaScript Objects.
Also there are a tons of questions in stack about this issue about inheritance in javascript.
Also as talked in the comments if you want someone to criticize your code take a look at Code Review
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an array like this
var myArray = [
"J20J205147902_B_B716202",
"R20Q205147902_F_B716202",
"P20W205147_902_alternate1",
"M20K205147_902_alternate4",
"F20G205147_902_alternate3",
"K20J205147_902_alternate2",
"L20H205147_902_main"];
I want to sort this array by this pattern
var map = {
"_F_":1,
"_main":2,
"_alternate1":3,
"_alternate2":4,
"_alternate3":5,
"_alternate4":6,
"_alternate5":7,
"_B_":8
};
So, the output should be like this
"R20Q205147902_F_B716202",
"L20H205147_902_main",
"P20W205147_902_alternate1",
"K20J205147_902_alternate2",
"F20G205147_902_alternate3",
"M20K205147_902_alternate4",
"J20J205147902_B_B716202"
You can use a custom sorting comparator function as follows:
var myArray = [
"J20J205147902_B_B716202",
"R20Q205147902_F_B716202",
"P20W205147_902_alternate1",
"M20K205147_902_alternate4",
"F20G205147_902_alternate3",
"K20J205147_902_alternate2",
"L20H205147_902_main"];
var map = {
"_F_":1,
"_main":2,
"_alternate1":3,
"_alternate2":4,
"_alternate3":5,
"_alternate4":6,
"_alternate5":7,
"_B_":8
}
myArray.sort((...args) => {
const [a, b] = args.map(str => Object.keys(map).find(key => str.includes(key)))
return map[a] - map[b];
})
console.log(myArray)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a json file like below:
{ "userdata": { "userid123": {"uname": " john", "uemail": "john#mail.com"}, "userid124": {"uname": "sam", "uemail": "sam#mail.com"} }
I want to parser user details if someone go to url http://example.com/?userid123
So only details of userid123 (which is in the url, get it from there) will be shown.
Json string you added to the question is wrong.
If you need to get the string after the question mark and test if the corresponding value exist or not, you can write:
var js = {
"userdata": {
"userid123": {"uname": " john", "uemail": "john#mail.com"},
"userid124": {"uname": "sam", "uemail": "sam#mail.com"}
}
};
var sp = window.location.search.substr(1);
//for testing purposes
sp='userid123';
if (js.userdata[sp] !== undefined) {
console.log('uname: ' + js.userdata[sp].uname + ' uemail: ' + js.userdata[sp].uemail)
}
First of all you have to save userId to variable like
var userId = location.search.substr(1);
.substr(1) <- this will remove ? from result of location.search();
Now since you are using jquery you can access your json (and user data) as below
$.getJSON( "users.json", function( data ) {
var userData = data[userId]; // your user data
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting data in array like this, left side are account name and right one are subscriptions.
7ef:" 3sdc 12exf"
12ef:" 8ecg"
10ef:" 3ecf 3egf 3elm 3ecf 3egf 3elm "
mean 7ef index have 2 strings of data and there is space between both. and 10ef have 6 strings of data.I need this data in form of like
7ef:" 3sdc"
7ef:" 12exf"
12ef:" 8ecg"
10ef:" 3ecf "
10ef:"3egf"
10ef:"3elm"
10ef:"3ecf"
10ef:"3egf"
10ef:"3elm "
As I have to sent it to make its csv file. How Can I do that in javascript ?
Code of creating this is like
foreach ($subscriptions as $subscription) {
$str=$str.' '.$subscription->uuid;
}$anew[account[$i]]=$str;
EDIT :
Now after reading comments can some one tell me how can I make it like
0:" 3sdc"
1:" 12exf"
2:" 8ecg"
like I will save account for later and now I want to arrange them all.
This won't be possible because Javascript Object at same level can have only have unique key, so it will just override the value
SUGGESTED:
use the structure like this
{
7ef:["3sdc", "12exf"],
12ef:["8ecg"],
10ef:["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
}
code :
for (var keys in a){
for (var data in a[keys]){
console.log(keys + " : "+ data)
}
}
a is the var holding the above js object
Change your PHP code to produce a better structure:
$lst = [];
foreach ($subscriptions as $subscription) {
$lst[] = $subscription->uuid;
}
$anew[account[$i]] = $lst;
I suppose you have somewhere:
echo json_encode($anew);
This will give you the following structure in JavaScript:
{
"7ef": ["3sdc", "12exf"],
"12ef": ["8ecg"],
"10ef": ["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
}
To output this as CSV, you could do this (assuming the data is in response):
const response = {
"7ef": ["3sdc", "12exf"],
"12ef": ["8ecg"],
"10ef": ["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
};
const csv = Object.keys(response).reduce( (acc, key) =>
acc.concat(response[key].map( uuid => [key, uuid].join(", ") ))
, []).join("\n");
console.log(csv);