I've been trying to create a string, usable by JSON, to insert a set of data into MongoDB. Note that the data is being input, all the information is correct.
However, "finalString" is being treated as an individual variable, and is being input as "finalString" : undefined, and then carries on right into the next value, i.e. undefinedStudent...., rather than undefined, "Student...".
After that, however, the data is input correctly and mongo treats the rest of the variable like a statement. How would I go about getting my script to recognize the variable as one entire statement.
mclient.connect(url[0], function(err, db) {
var dataToJSONFormat = "";
for(var i = 0; i < properties.length; i++) {
dataToJSONFormat += properties[i] + " : '" + values[i] + "'";
if(i < properties.length - 1) dataToJSONFormat += ", ";
}
write("OrderData: {" + JSON.stringify(dataToJSONFormat) + "}");
var finalString = dataToJSONFormat;
db.collection(url[1]).insert(
{
OrderData : {finalString}
}
);
console.log(dataToJSONFormat);
console.log("Data input successful");
db.close();
});
In JavaScript you don't need to generate the object from string. You can just use the object literal notation something like below.
mclient.connect(url[0], function(err, db) {
var data = { OrderData:{} }
for(var i = 0; i < properties.length; i++) {
//this does the trick. You can assign key values to object on the fly. using obj[key] = value
data.OrderData[properties[i]] = values[i];
}
db.collection(url[1]).insert(data);
console.log("Data input successful");
db.close();
});
Check this jsFiddle that shows the concept.
Related
I have two arrays.
var fruits = [];
var tasks = [];
When I enter a value in the text field it fires a function that pushes the value to an array. It then fires a separate function that stringifies the array and saves it in local storage. ("when" is my alias for document.addeventlistener).
when(toDo, "keypress", function(event){
if (event.key == "Enter" || event.keyCode == 13) {
pushArray();
stringifyArray(fruits);
toDo.value = "";
}
});
// function that adds new task to the array
function pushArray(){
var newtask = new Task(toDo.value, "No note yet");
fruits.push(newtask);
}
// function that stringifies given array and stores it in local storage
function stringifyArray(array){
var makeString = JSON.stringify(array);
var setItem = localStorage.setItem("tasks", makeString);
}
When I loop through the first array and try to display object.Name and .Note in a div it works fine:
when(button, "click", function(event){
demolist.innerHTML = "";
for(i=0; i< fruits.length; i++){
demolist.innerHTML += fruits[i].Name + " " + fruits[i].Note + "<br>";
}
});
But when I fire a function that parses that array, populates the second and tries to loop through it in the same manner I get "undefined undefined" even though I can see that the array contains all the objects I submitted when I check the console.
function parseArray(){
var getArray = localStorage.getItem("tasks");
var parseObj = JSON.parse(getArray);
tasks.push(parseObj);
}
when(button2, "click", function(event){
function parseArray()
demolist2.innerHTML = "";
for(i=0; i< tasks.length; i++){
demolist2.innerHTML += tasks[i].Name + " " + tasks[i].Note + "<br>";
}
});
https://jsfiddle.net/bjxs3LdL/
(NO JQUERY SOLUTIONS PLEASE)
I am new to coding and stackoverflow so forgive the long post.
Fix your parseArray() function by changing
tasks.push(parseObj);
to
tasks = parseObj;
EDIT: Sorry for all the edits, it's hard to wrap my around the control flow. To fix the issue of the first note not getting saved, add a stringifyArray(fruits); call to the end of your submitNote() function.
The parseArray call is wrong, try rewiriting button2 listener like this:
when(button2, "click", function(event){
parseArray();
demolist2.innerHTML = "";
for(i=0; i< tasks.length; i++){
demolist2.innerHTML += tasks[i].Name + " " + tasks[i].Note + "<br>";
}
});
Otherwise, your code needs a redesign, but that's for another opportunity.
I have a form that works on IE that connects to a database. This works great. However, when I fill in the text boxes the data does not get transferred to the database. I have checked the field.value and it always equals what I input. The record set is pointing at the right table, as I have checked the names of the rows as it goes through each iteration. However, the data from the boxes never actually gets updated?
function parkRecordSet(){
var conn = accesDB()
var cmdDI = CreateCommand(conn, "tblPark");
var rsDI = CreateRecordSet(cmdDI);
inputData(rsDI)
UpdateData(conn, rsDI);
}
So this part works well. The input data takes in an array that will be passed into the function below as recordData. I put an alert to see if the values I was getting were correct.
function AddNewDataToRecordSet(rs, recordData){
rs.AddNew();
var myFields = rs.Fields;
var myEnum = new Enumerator(myFields);
var indexRecordData = 0;
var fieldItem;
myEnum.moveFirst();
for ( ; !myEnum.atEnd(); myEnum.moveNext() ){
fieldItem = myEnum.item();
//alert( "Field Name is: " + fieldItem.Name + " Value is: [" + fieldItem.Value + "]" + "Attr=" + fieldItem.Attributes)
if (fieldItem.Attributes & adFldIsNullable) { //bit-wise test
fieldItem.Value = recordData[indexRecordData];
//alert(fieldItem.Value)
indexRecordData = indexRecordData + 1;
} //end of IF
rs.Fields("ParkName") = "In Process"
}
return;
}
function UpdateData(conn, rs) {
conn.BeginTrans();
rs.Update();
conn.CommitTrans();
// Performing the update
rs.Close();
return;
}
I have to use regular expressions to replace or append a query to a url with the function adjustUrlParameter(url, param). If the same query exists in the URL, it should replace the query with param (i.e. ID=501 should replace ID=200 in google.com?ID=200). If no query exists, it should simply append the query to the end of the url. Finally, if a query does exist but of a different type, it should append the query and separate it from the pre-existing query with a '&'. Here's an example:
adjustUrlParameter('google.com?ID=501', 'TYPE=444') // => 'google.com?ID=501&TYPE=444'
My code isn't replacing the same query type. It is returning 'google.com?ID=501&ID=200' instead of returning 'google.com?ID=200'. Here's my code:
var adjustUrlParameter = function(url, param) {
var urlQuery = url.match(/\w+\W+/g);
for (var i = 0; i < urlQuery.length; i++) {
if (param === urlQuery[i]) {
return url.replace(/\?.+$/, '?' + param);
}
}
if (url.match(/\?/)) {
return url + "&" + param;
} else {
return url + "?" + param;
}
};
How do I get adjustUrlParameter('google.com?ID=501', 'ID=201') to return the proper result ('google.com?ID=201')?
The problem is that the if statement never returns true. Put some console.logs in the for loop and watch it. You'll see when urlQuery[i] returns "ID=" param returns "ID=444". They are not equal.
console.log("parameter:"+param); //parameter:ID=444
console.log("url_query: "+urlQuery[i]); //url_query: ID=
If you change your for loop like below it replaces the query parameter with the same type:
for (var i = 0; i < urlQuery.length; i++) {
console.log("parameter:"+param);
console.log("url_query: "+urlQuery[i]);
var paramType = param.split("=");
console.log("paramType"+paramType);
var tmp = paramType[0]+"="; //since urlQuery[i] always has a character at the end
console.log(tmp);
if (tmp === urlQuery[i]) {
return url.replace(/\?.+$/, '?' + param);
}
}
When you run adjustUrlParameter('google.com?ID=501', 'ID=444') the output is "google.com?ID=444"
You want to compare the names of the queries, not the values they contain too.
Say you pass in id=200 as param, you want to find and replace from id in the existing url. That means that we don't care about the value of id. If that is the case, we can split by ? or & to get a list of all of the queries. We start looping at 2 because 0 and 1 are the base url and the ?. We also jump 2 with every iteration to skip the preceding &. Lastly, we make sure to split each query with = and use [0] or the first half to get that name that we care about.
You could do something like this:
var adjustUrlParameter = function(url, param) {
var urlQuery = url.split(/(\?|\&)/)
, thisQuery = param.split(/\=/)[0]
for (var i = 2; i < urlQuery.length; i = i + 2) {
if (thisQuery === urlQuery[i].split(/\=/)[0]) {
return url.replace(/(\?|\&).*$/, '?' + param);
}
}
if (url.match(/\?/)) {
return url + "&" + param;
} else {
return url + "?" + param;
}
};
I expect this will be very simple for someone. I am trying to pass some key value pairs as a query to Parse.com javascript API. The documented format is as follows and works fine:
var query = new Parse.Query("testUser");
query.containedIn("facebookID",["10101185732529914", "10101185732529915"]);
query.find()
.then(function(result){
console.log(result);
});
However I want to pull the IDs from an array and pass them in so I have used the following code to do so (the x variable being the array):
var text = '';
for (index = 0; index < x.length; index++) {
text += '"' + x[index]['$id'] + '"';
}
text += '';
var requestString = text.replace(/""/g, '", "');
If I console.log(requestString);this shows the data in the format I need, e.g. "10101185732529914", "10101185732529915"
As such the updated request code with the variable instead of the text is now:
var query = new Parse.Query("testUser");
query.containedIn("facebookID",[requestString]);
query.find()
.then(function(result){
console.log(result);
});
This however does not work, I am assuming this is due to the format of the variable. The relevant section of Parse.com API docs is here...https://parse.com/docs/js/guide#queries-query-constraints
Any help with this would be greatly appreciated.
Thanks
Ant
Sorted the problem, it wanted an array not a string, as such...
var text=[];
for (index = 0; index < x.length; index++) {
text.push(x[index]['$id']);
}
var requestString = text;
and
var query = new Parse.Query("testUser");
query.containedIn("facebookID",requestString);
query.find()
.then(function(result){
console.log(result);
});
Thanks
Ant
I want to get values of all fields in a variable separated by a comma. For example: 1,2,3
The following code will work fine, but it only adds the comma at end of the last value also. How can I remove that?
fields = $('.wrap').find('.text');
var data = '';
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value + ',';
}
});
alert(data);
JSFiddle:
http://jsfiddle.net/cn5Gt/
I always use arrays for these kind of things:
var fields = $('.wrap').find(".text[value!='']");
var data = [];
fields.each(function() {
data.push($(this).val());
});
alert(data.join(','));
You can push elements on array than just use join() method.
fields = $('.wrap').find('.text');
var data = [];
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data.push(value);
}
});
alert(data.join());
Try the code below, using the i which is the loop index and test against the length of the jQuery object.
fields = $('.wrap').find('.text');
var length = fields.length;
var data = '';
fields.each(function(i) {
var value = $(this).val();
if ( value != '' ) {
if(i === length-1) { //The last one
data += ' ' + value;
} else {
data += ' ' + value + ',';
}
}
});
Updated fiddle
You could just remove the final character afterwards?
data = data.substr(0, data.length - 1);
http://jsfiddle.net/cn5Gt/3/
Simplest of all:just replace your last line with the below line
alert(data.slice(0,-1));//where data is string
http://jsfiddle.net/cn5Gt/7/
DOC MDN : slice
How about something like this:
var data = $('.wrap').find('.text')
.map(function(i,el){ return el.value || null; })
.get().join(", ");
Demo: http://jsfiddle.net/cn5Gt/11/
jQuery's .map() method will "Pass each element in the current matched set through a function, producing a new jQuery object containing the return values." You can still include your if ( value != '' ) { test in the callback function because if your function returns null or undefined then .map() will not use that particular value. (I've used || null above as a shortcut to an if/else structure.)
Call .get() (or .toArray()) on the result and you'll have an actual array, which means you can then use the Array .join() method to form a string with the values comma separated.
If you need to do other processing on each item besides just getting the value you could stick with the .each() loop and add the values to an array that you then join after the loop (like some of the other answers), or just use the string .slice() method to remove the trailing comma and space characters.
Try this:
Using the length function to determine the position of the each
var fields = $('.wrap').find('.text');
var len = fields.length;
var data = '';
fields.each(function(index, element) {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value;
if (index != len - 1) {
data += ',';
}
}
});
alert(data);