Filling arrangement from a database - javascript

I need to fill an array with each of the values ​​for "name" and "nickname" taken from a SQLITE database and show it in an alert.
This is for a project written in JavaScript in titanium appcelerator.
This is the code:
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push = {
name: name,
nickname: nickname
};
fightersRS.next();
}
alert(setFighters);
The idea is that the alert displays all comma separated values, for example:
"muhammad ali, rocky balboa, ten shin han, etc ...."
How I can do it? my code does not work.

Change your code as follows
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push({"name": name, "nickname": nickname}); //This is the correct syntax for pushing an element to the array
fightersRS.next();
}
You can display the elements using a for loop as follows
for(var i=0; i <setFighters.length;i++){
alert("Name = " + setFighters[index].name + " Nickname= " + setFighters[index].nickname);
}
If you want to display their name with comma, try the following
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
setFighters.push(name);
fightersRS.next();
}
var fighters = setFighters.join(",");//Joining the array elements with comma
alert(fighters); //Will display all names with a comma
Look at javascript join method

Use a for loop or inside the while loop only create a string appending all the values with comma.
Fetching all the data from an array with comma is not possible.
Here's an asccociative array example from stack over flow .. you can have your own for loop or use the while loop you are creating
Associative array and fetching data
Thanks

Related

Creating array with multiple objects Javascript from XML data

I have a problem approaching this problem and I'm unsure in how to solve it. My XML looks like this:
<Order>
<OrderLines>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
What I want to do is create an array, and fill it with objects with articleNumber, serialnumbers. Where I'm stuck is getting all the serialNumbers from a node to the corresponding article number.
Edits after comments:
Expected output: An array filled with the objects with ArticleNumber, Corresponding serial number. One serial number = one object.
Current Code:
//Create Article List
var artList = [];
//Get articles
var nodeArticleNo = xmlDoc.getFirstNode('//ProductLine/ManufacturerArticleNo');
while(nodeArticleNo != null) {
var artNo = xmlDoc.getNodeText('//ProductLine/ManufacturerArticleNo');
//Get Serials
var nodeSerialNumber = xmlDoc.getFirstNode('//Serials/SerialNumber');
while(nodeSerialNumber != null){
var serialNo = xmlDoc.getNodeText('//Serials/SerialNumber');
artList.push({ArticleNumber: artNo, SerialNumber, serialNo});
nodeSerialNumber = xmlDoc.getNextNode(nodeSerialNumber);
}
nodeArticleNo = xmlDoc.getNextNode(nodeArticleNo);
}
This is how I have been trying to solve it but I hate the while in a while and it is not working as intended
Thank you!

Creating dynamic Prepared Statements to insert into database

I'm trying to write one row of data into a Google Cloud SQL database, using a prepared statement as described here:
https://developers.google.com/apps-script/guides/jdbc
I have the data stored in an object called valuesByTitle, which looks like this:
{NAME: 'fun event', LOCATION: '123 Main St.'}
The data is inserted into the SQL table if I write everything out like this:
var conn = getConnection(); // connects to db
var stmt = conn.prepareStatement('INSERT INTO events '
+ '(NAME, LOCATION) values (?, ?)');
stmt.setString(1, valuesByTitle['NAME']);
stmt.setString(2, valuesByTitle['LOCATION']);
stmt.execute();
}
However, I would like to automate the process, so I don't have to change the code each time the variables change.
I have two new variables, one for the column names and one for a set of place holders (e.g. "?") for the insert statement.
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
};
Using these, this prepared statement should automatically insert whatever is in the valuesByTitle object (assuming all the values are string values):
var conn = getConnection();
var stmt = conn.prepareStatement("INSERT INTO events (" + columns.join(",") + ") VALUES (" + placeholders.join(",") + ")");
for (i = 0; i < columns.length; i++) {
stmt.setString(i+1, valuesByTitle[columns[i]]);
}
stmt.execute();
For some reason, it's not inserting the data. Surprised not to find any examples either. Is the logic off or is it just not possible to do?
Thanks.
All your code is OK, you simply forgot to close the map() bracket i.e.
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
};
should be
var columns = Object.keys(valuesByTitle);
var placeholders = columns.map(function(column) {
return "?";
});
(note the ending bracket after return "?";})

count the number of rows in 2d array

Description:
I am adding the data in my 2D array like the following
my_2d_array['user1'] = {'id':name,'socket':socket};
my_2d_array['user2'] = {'id':name,'socket':socket};
This 2D array keeps the record of all the connected users id and their respective sockets ...
I want to display the number of users connected .. So far to do that would be to count the number of rows in the array and display it
I have tried following:
my_2d_array[].length; // this gives nothing
my_2d_array.length; // this outputs 0 (as number)
What should I do to get the number of rows
UPDATE
I declared my array like this
var my_2d_array = [];
This could work for you
// initialize
var my_2d_array = {};
// add users
my_2d_array["user1"] = ...
my_2d_array["user2"] = ...
// get number of users
Object.keys(my_2d_array).length;
//=> 2
You should consider using users instead of my_2d_array though. It communicates better and the actual data type is an Object, not specifically an Array.
Use push method
my_2d_array.push({'id':name,'socket':socket});
my_2d_array.push({'id':name,'socket':socket});
And my_2d_array.length to get the count
It looks like you are trying to figure out how many keys are in your javascript object my_2d_array.
You should be able to use Object.keys()
Here is a JsFiddle.
var my_2d_array = {};
var name = "Hello";
var socket = "World";
my_2d_array['user1'] = {'id':name,'socket':socket};
var name = "Hello2";
var socket = "World2";
my_2d_array['user2'] = {'id':name,'socket':socket};
alert( Object.keys(my_2d_array).length );

How to generate an array of arrays in Javascript?

So given:
var person = {name: "", address: "", phonenumber: ""}
I want to create a loop to receive user input (until they decide they don't want to input anymore information and input nothing or click cancel). I'd also like to use the person object as a prototype.
So I guess an object just to store the name/address/phone number of an arbitrary number of people. My logic for this would be to dynamically add an entire array to an object for every iteration of my loop. My code looks something like this:
var person = {name: "", address: "", phonenumber: ""}
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
//move input into the person array.
//person to look like {name = "mike", address = "main", phone = "123456789"}
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}
I've been trying to dynamically generate something like this:
customer =
[{name, address, phone},
{name, address, phone},
{name, address, phone}]
and then be able to access it and print it. i've been trying to access it with
console.log(customer[0].phone);
unfortunately im getting an error.
sorry for my error, console.log prints nothing so it seems like there's nothing stored in customer[0].phone.
i can't get access to any of the data that i've prompted the user for and saved in variables. when i use the alert function all i get is a blank box. whenever i try to print customer i get the message [object Object]or something along those lines
var customer = [];//create array
var person = {};// create object
var input = prompt("...");//your prompt
var results = input.split(", "); //create an array from the input
person.name = results[0];//add result with 0 index
person.address = results[1];//add result with 1 index
person.phone = results[2];//add result with index 2
customer[0] = person;//add the person object to the array.
The above code should do as you wish. I'm having a hard time seeing why you would iterate a prompt to the same user?? So try this first then go on.
http://jsfiddle.net/zkc2swmp/1/
Don't go irratating your users with prompt boxes, use a form. Also don't iterate something like that, and your condition in the for loop basically creates an infinite loop which is also bad
My code could be a lot better, such as if conditions, and exactly how to use this with a form. Though frankly it seems as though you are far from that. So I've started you off, try it and see if you can implement this the way you want, then comment with suggestions for helping you do something else.
First of all, every time you are assigning person to customer i.e.
customer[i] = person;
all other objects are getting modified as your breaking point is input== "" so all objects are modified with null values.
in start you are defining property as "phonenumber" and in the end u r putting value in "phone".
correct code shud be :
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
var person = {};
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}

Need to place comma after each field with proper validation

I have 3 fields for user input.. say textbox1,textbox2,textbox3. What i need to do is represent them like this if values are not empty:
Albany, New York, USA
The last textbox value shouldnt have a comma after that. I was able to do it with an associative array but the problem is i couldnt find a way to detect if it was the last value and after that the comma need not appear.Here is what i did
var addressObjToFormat= {};
addressObjToFormat.City = $("#companyentry").find("#City").val();
addressObjToFormat.State = $("#companyentry").find("#State").val();
addressObjToFormat.Country = $("#companyentry").find("#Country").val();
var formattedAddress = $Utils.mapInfoMarkerAddressFormatter(addressObjToFormat);
mapInfoMarkerAddressFormatter = function mapInfoMarkerAddressFormatter(arraddressObjToFormat) {
var formattedAddress = '';
for (var key in addressToFormatObj) {
if (addressToFormatObj.hasOwnProperty(key)) {
if (addressToFormatObj[key] != '') {
formattedAddress += addressToFormatObj[key] + ',';
}
}
}
alert(formattedAddress);
}
Above code gives me result as :
Albany, New York, USA,
Mumbai, Maharshtra, India,
What i want is it should be able to check if its the last field incase if a textbox is left empty and place comma accordingly after each value. Or is there a better way to do this?
You can use substring, jsfiddle
formattedAddress = formattedAddress.substring(0, formattedAddress.length-1);
or
you can save all values in an array and use Array.join eg.
var arr = ['item1','item3','item3','item4'];
formattedAddress = arr.join(' ,');
There are multiple ways to do this
After all your processing, you can just trim off the last ',' as using a regex
formattedAddress = formattedAddress.replace (/,$/g, "");
Alternatively, you can just push your strings into an array and then join them all.
var tmp = [];
for (var key in addressToFormatObj) {
if (addressToFormatObj.hasOwnProperty(key)) {
if (addressToFormatObj[key]) { // your condition
tmp.push(addressToFormatObj[key]);
}
}
}
var formattedAddress = tmp.join(',');
var formattedAddress = addressToFormatObj.join(',');
The array function join() uses its first parameter as a glue to put in between array segments.

Categories

Resources