I am writing a cleansing function which will delete all invalid docs from collection. For this I have an idea to push invalid _id values into array variable and delete with $in.
function(scan){
var err
for(var n=1;n<scan;n++){
var doc = db.zeroDimFacts.findOne({_id:n}) ,nKeys =0;
for(k in doc)
nKeys++
if(nKeys <5)
err = n.toArray()
}
After I push all values to err Array, I have a script to delete matching docs. However, there is something missing with the code which throws me error at n.toArray() .
Can someone help me to correct the code?
function(scan) {
var doc;
var nKeys;
var err = [];
for(var n = 1; n < scan; ++ n) {
doc = db.zeroDimFacts.findOne({_id: n})
nKeys = 0;
for(k in doc) {
++ nKeys;
}
if(nKeys < 5) {
err.push(n);
}
}
return err;
};
Pay attention to findOne() call. When it returns null, n will get into the array which seems undesirable to me.
You can use findByIdAndRemove({criteria}) and depending on return value you can have the logic.
Related
I am using p5 loadJSON to import data, the data gives an array with so many records and sub-arrays.
For example, data.records[i].form_values["94d5"] gives me a name.
I am currently using a for loop to go through data.records.length and give me an array of some key pieces of data relative to each record I want to see.
Problem:
I want to loop through the records and get the value of:
data.records[i].form_values["94d5"].choice_values["0"], but some records don't have form_values["94d5"], for example. I just want to skip empty sections (leave undefined like empty items) insted i get an error that choice_values is undefined.
My loop is:
function gotData(data){
var i = 0;
var statusFind = data.records[i].status;
for(i = 0; i < data.records.length; i++) {
var returned = [data.records[i].form_values["6f71"], data.records[i].form_values.b059, data.records[i].form_values["94d5"], data.records[i].form_values.b62d, data.records[i].form_values["3493"].choice_values["0"], data.records[i].status, data.records[i].form_values.af80];
for (j = 0; j < returned.length; returned++){
if (returned[j] == searchKey) {
var result = [returned[0], returned[1], returned[2], returned[3], returned[4], returned[5], returned[6]];
array.push(result);
write();
}
}
}
}
I implemented a Java code for permutation combination a string with input str= "word1 word2 word3" then output as:
arr[0]= "word1 word2"
arr[1]= "word1 word3"
arr[2]= "word1 word2 word3"
arr[3]= "word2 word1"
arr[4]= "word2 word1 word3"
arr[5]= "word2 word3 word1"
arr[6]= "word3 word1"
arr[7]= "word3 word1 word2"
arr[8]= "word3 word2 word1"
This is Java code:
private static void permute(String[] ss, boolean[] used, String res, int level, List<String> list) {
if (level == ss.length && res != ""){
list.add(res);
return;
}
for (int i = 0; i < ss.length; i++) {
// Check if the string is currently used
if (used[i]) {
continue;
}
// Check if res is empty or a single word
if(level > 1)
list.add(res);
used[i] = true;
permute(ss, used, res + " " + ss[i], level + 1, list);
used[i] = false;
}
}
public static List<String> PermuteWords(String s){
String[] ss = s.split(" ");
boolean[] used = new boolean[ss.length];
String res = "";
List<String> list = new ArrayList<String>();
permute(ss, used, res, 0, list);
return list;
}
When converting to JS code, I don't know what are errors in this code:
function permute(ss, used, res, level, list){
if(level==ss.lenght&&res!==""){
list.add(res);
return;
}
for(var i=0; i<ss.lenght; i++){
if (used[i]===true){
continue;
}
if(level>1){
list.add(res);
used[i]=true;
permute(ss, used, res+" "+ss[i], level+1, list)
used[i]=false;
}
}
}
function permuteword(s){
var ss;
for(var i=0; i<s.length;i++){
ss[i]=s[i];
}
var used;
for(var j=0; j<s.length;j++){
used[j]=false;
}
var result;
permute(ss, used, res, 0, result);
return result;
}
Java and Javascript may sound almost the same but they aren't. They take different appoaches doing different things. If in Java You are checking the console for errors on running the program, then in Javascript you can check for the errors in the browser console (open console with F12)
POPULATE ARRAY
Javascript arrays don't have add() method. To add a value to it, use push:
list.push(res)
POPULATE ARRAY #2
In permuteword() function you are trying to populate variable ss that is not initialized. Compiler doesn't understand where you want to put that value. Initialize ss as an empty array:
var ss = [];
TYPOs
In the first for loop you have ss.lenght. Fix that. Always check for the typos.
EXTRA
In permuteword() you are passing res to the permute() function although you don't have it defined in the function. Things will work if res is a global variable defined outside of the functions.
And take advantage of that browser console. Every Javascript developer (from noobie to pro) has it always open!
I ran the code in couchdb and cloudant that showed the general errors that i missed checking the syntax. I modified the code as:
function permute(ss, used, res, level, list){
if(level==ss.lenght&&res!==""){
list.push(res);
return;
}
for(var i=0; i<ss.length; i++){
if (used[i]===true){
continue;
}
if(level>1){
list.push(res);
used[i]=true;
permute(ss, used, res+" "+ss[i], level+1, list)
used[i]=false;
}
}
}
function permuteword(s){
var ss=[];
for(var i=0; i<s.length;i++){
ss[i]=s[i];
}
var used=[];
for(var j=0; j<s.length;j++){
used[j]=false;
}
res="";
var result=[];
permute(ss, used, res, 0, result);
return result;
}
function(doc){
var list=permuteword("word1 word2 word3");
for(var i=0; i<list.length; i++){
index("default", list[i],{store, true});
}
}
However, i still meet the errors as:
{"error":"{nocatch,{compilation_error,<<\"Expression does not eval to a function. ((new String(\\"function permute(ss, used, res, level, list){\\r\\n if(level==ss.lenght&&res!==\\\\"\\\\"){\\r\\n list.push(res);\\r\\n return;\\r\\n }\\r\\n\\r\\n for(var i=0; i1){\\r\\n list.push(res);\\r\\n used[i]=true;\\r\\n permute(ss, used, res+\\\\" \\\\"+ss[i], level+1, list)\\r\\n used[i]=false;\\r\\n }\\r\\n }\\r\\n}\\r\\nfunction permuteword(s){\\r\\n var ss=[];\\r\\n ss=s.split(\\\\" \\\\");\\r\\n var used=[];\\r\\n for(var j=0; j>}}","reason":"[{couch_os_process,prompt,3,[{file,\"src/couch_os_process.erl\"},{line,65}]},\n {dreyfus_index_updater,update,2,\n [{file,\"src/dreyfus_index_updater.erl\"},{line,42}]}]"}
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.
I have an object in my javascript which looks like this:
{"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}},
// .....
What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently.
I have an array for longitude, latitude, color and level.
So I have tried the following:
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
alert(result.data[size]);
}
-->But this only alerts me "[object Object]"
success: function(result){
var size = 0, key;
for (key in result) {
for(var attr in key){
alert(attr['latitude']);
}
}
}
-->This gives me Undefined result[key]
I have checked that the size of my object is only 1 thru these codes
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
}
alert(size);
I believe that only "data" is being read. And others that are inside "data" are disregarded.
I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.
UPDATE
Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched
t
Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color "#040098"
latitude "14.6204083333333"
level "35"
longtitude "121.0508"
I tried this
for (key in result) {
if (result.hasOwnProperty(key)) size++;
console.log(result.data[size]['level']);
}
--> but it says undefined
based on the structure of my object which is
data:[{"t":{'others'},'others'...]
How am I to read everything inside "data"? Each "data" has "t".
Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):
for(var i=0; i<results.data.length; i++){
alert(results.data[i]['t']['latitude']);
// etc...
}
Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
var latitudes = [];
// and so on...
for (var idx in result.data ) {
if( result.data.hasOwnProperty(idx) ){
alert( result.data[idx]['t']['latitude'] );
// So you would do something like this:
latitudes.push ( result.data[idx]['t']['latitude'] );
// and so on...
}
}
}
Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.
var latitudes = $.map( result.data, function(n){
return n['t']['latitude'];
});
// and so on...
Assuming result is your object, this should just be a matter of iterating over your data array:
for (var i = 0; i < result.data.length; ++i) {
console.log(result.data[i].t.latitude);
...
}
It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?
var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}}
]};
var data = result.data;
var i, len, t;
for (i = 0, len = data.length; i < len; i++) {
t = data[length].t;
levels[i] = t.level;
longitudes[i] = t.longtitude;
latitudes[i] = t.latitude;
colors[i] = t.color;
}
See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.
var data = input.data,
result = {level: [], longtitude: [], latitude: [], color: []};
for (var i = 0, n = data.length; i < n; i += 1) {
var info = data[i].t;
for (var property in info) {
if (info.hasOwnProperty(property)) {
result[property].push(info[property]);
}
}
}
console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);
This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).