Loop through severals objects js - javascript

I want to retrieve data from an object, and I need to make several iterations. I have another object inside the first.
Here is what I try to do
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers + '<div class="detail"></div>' + '<br>';
$('.test').append(itemList);
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$('.detail').append(itemDetail);
}
}
But when I did this code, the first element append, receive all the key/value from the others details objects. I only want to display the details object related with his site parent site object.
Here is a fiddle : http://jsfiddle.net/JeremDsgn/7EX6M/
Thanks!

That's because your selector $('.detail') selects all elements with class detail.
Try using the DOM instead of strings. I give you this as a personal advice. I used to append HTML via strings just like you're doing it now. Since I started using DOM objects as they are actually meant to be used, the javascript language became times more pleasant to work with.
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers;
var details = document.createElement('div');
details.className = 'detail';
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$(details).append(itemDetail);
}
$('.test').append(itemList).append(details);
}

Related

mongodb batch insert - Javascript not working

I want to insert bunch of records into a collection, but instead of document at a time I want to do it like a batch using "insertMany()". I wrote the script as follows:
var batch = [];
for (i=0; i<10; i++) {
names=["exam", "essay", "quiz"];
for (j=0;j<3;j++) {
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
if (mod i%3 == 0) {
batch = batch.slice(0, batch.lenght(-1));
db.scores.insertMany( batch )
batch=[];
}
}
}
The above code is not working. There are two issues: first, the array item have double quotes around them and second, the "slice" is not taking effect.
Need help in fixing the Javascript.
There are a couple of issues here:
the array item have double quotes around them
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
You want to create an object rather than a string. batch = { student: i, type: names[j], score: ..} will create an object for you.
the "slice" is not taking effect
batch = batch.slice(0, batch.lenght(-1));
You've misspelled length, and length is a property rather than a function. batch.slice() will copy the array (but you're resetting it so it's not actually necessary).

binding variables to SQL statements using node-sqlite3

I am trying to convert this:
var query_string = 'SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_A = "' + item + '" ' +
'UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_B = "' + item + '";';
db.each(query_string, function (err, row) {
...
To this:
var query_string = "SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'" +
" UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'";
var placeholders = {
$table: organism + PIPE_output_table,
$score_type: score_type,
$score: cutoff['range'],
$protein: item
};
var stmt = db.prepare(query_string, placeholders, function(err) {
console.log(err);
stmt.each(function(err,row) {
...
})
}
but I keep getting this error:
Error: SQLITE_ERROR: near "$table": syntax error
But I am not sure what is syntactically wrong here since the format is as I have seen it in the API documentation. I have tried '?', '#', and ':' before each variables but none seem to be recognized.
What's wrong in my code?
Bind parameters only work for values in the WHERE clause. Table and column names (collectively called "identifiers") won't work.
"SELECT foo FROM bar WHERE this = $that" # OK
"SELECT foo FROM bar WHERE $this = 'that'" # Not OK
Normally you'd work around this by escaping and quoting identifiers and inserting them into the query. A good database library has a method call for this...
var this = db.quote_literal(input_column);
'SELECT foo FROM bar WHERE ' + this + ' = ?'
Unfortunately, node-sqlite3 doesn't appear to have one. :(
SQLite does provide a quoting function, the %w operator, but node-sqlite3 doesn't appear to make it available.
You'll have to write your own. Follow the instructions from this answer in Python and convert them to Javascript.
Ensure the string can be encoded as UTF-8.
Ensure the string does not include any NUL characters.
Replace all " with "".
Wrap the entire thing in double quotes.
I'm not very good with Javascript, so I'll leave you to code that.

JS var inside query does not work when stringed together

I have the following code which is really bloated
$(".field-name-field-parts-status .field-item:contains('Submitted'), .field-name-field-parts-status .field-item:contains('Saved'), .field-name-field-parts-status .field-item:contains('HMNZ Approved')").addClass('btn-primary');
I tried to neaten it up by adding a var
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
So it looked like this
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
But it stopped working, can anyone tell me what I did wrong? Thanks
Because you are trying to add a jQuery object and a string together. It does not work like that.
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
should be a string
var fieldItemStatus = ".field-name-field-parts-status .field-item";
other option is to use filter.
You need to use .filter()
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
fieldItemStatus is an object so
fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved') will create a string like [Object object]:contains('Submitted'), [Object object]:contains('Saved'), [Object object]:contains('HMNZ Approved')
remove $ in front for fieldItemStatus
var fieldItemStatus = ".field-name-field-parts-status .field-item";
Because you want to use a jQuery Object to concat string. The right way to do this is using string all the time.
var fieldItemStatus = ".field-name-field-parts-status .field-item";
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
You could use the filter method:
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
Another option is using the filter callback function:
var items = ['Submitted', 'Saved', 'HMNZ Approved'];
fieldItemStatus.filter(function(_, el) {
return items.some(function(item) {
return el.textContent.indexOf(item) > -1;
});
});
.
A more procedural approach. This way if you want to easily change the selectors, just change the contains array. You could turn this into a function to easily retrieve your selector on demand elsewhere in the script.
var contains = ['Submitted','Saved','HMNZ Approved'];
var selector = '';
for(var i = 0; i < contains.length; i++) {
selector += '.field-name-field-parts-status .field-item:contains("' + contains[i] + ')';
if(i < contains.length - 1) selector += ', ';
}
$(selector).addClass('btn-primary');

Javascript variable, different values, same line

First of all, let me apologize for the title, as it isn't so explanatory, but I could not say it in another way.
The deal is: I am doing a javascript application, in which I have an object called "ocorrencia", which was defined like this:
var ocorrencia = new Object();
that object has several children, being filled by a method:
ocorrencia.idOcorrencia = ""+ year + month + day + hour + minute + second + milisec;
idOcorrencia is the one I am having problems with, because I am running a DataBase insert with this value, and I use it 2 times in the same insert, like:
var sql = 'INSERT INTO OCORRENCIAS (id, ocorrencia, data, resolucao, urgencia, foto) VALUES (' + ocorrencia.idOcorrencia + ', "' + ocorrencia.descricao + '", "' + ocorrencia.data + '", "' + ocorrencia.resolucao + '", "' + ocorrencia.grauUrg + '", "' + ocorrencia.idOcorrencia + '.jpg"' +')';
The insert runs great, an I have all the data inserted in the DB, BUT "id" and "foto" (which were supposed to get equal values) are giving me different values by 2 or 3 miliseconds.
How can this happen, as I am not changing "ocorrencia.idOcorrencia" ?
This is beeing tested in an Android device.
EDIT: Tested on Windows browser and the problem doesn't appear to happen.
Thank you
I guess you fill idOcorrencia on runtime? So the lag is producing this difference.
Try using a hash for the id or set it before running the SQL-query.

OrientDB creating edges with Javascript function doesn't work

Good day,
I have two classes, one representing Hospital Admissions (called Ricoveri) and another one representing Discharges (called Dimissioni). Both have a property named Nosologico, representing an admission's unique identifier.
I have written a Javascript function, inspired by one of Luca Garulli's posts, to recursively create Edges between the two classes on the Nosologico property.
function code is as follows:
var g=orient.getGraph();
var b=g.command('sql','select from Ricoveri')
for(i=0; i<b.length; i++){
var id=b[i].getProperty("Nosologico").toString();
var rid=b[i].getId().toString();
var r=g.command("sql", "select from Dimissioni where Nosologico = '" + id + "'");
if(r.length>0){
var sql2="create edge dimesso from " + rid + " to (select from Dimissioni where Nosologico = '" + id + "')";
g.command('sql',sql2);
}
}
The function gets created successfully and executes without errors but it doesn't create any Edge.
Occasionally the whole server gets frozen and I have no other option than to kill it and restart it.
Is there anything wrong with the function?
Thanks.
QQ
first of all I suggest, if you heaven't done already, to create UNIQUE_HASH_INDEXes on nosologico property in both classes.
Then assuming that every nosologico in Dimissioni is also present in Ricoveri, and assuming that there are fewer Dimissioni than Ricoveri, the following query should be more efficient.
var g=orient.getGraph();
var b=g.command('sql','select from Dimissioni');
var id="";
var rid="";
var sql2="";
for(i=0; i<b.length; i++){
id=b[i].getProperty("Nosologico").toString();
rid=b[i].getId().toString();
sql2="create edge dimesso from (select from Ricoveri where Nosologico = '" + id + "') to " + rid;
g.command('sql',sql2);
g.commit();
}
let me know if this helps.
Ivan
maybe i'm wrong but, you do the query
var r=g.command("sql", "select from Ricoveri where Nosologico = '" + id + "'");
then you verify the length of the results, but it's pretty obvious that is > 0 (var id is coming from var b that is coming from the first query on Ricoveri).
So I'm saying, maybe in the var r you wanted to query from Dimissioni?
var r=g.command("sql", "select from Dimissioni where Nosologico = '" + id + "'");

Categories

Resources