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.
Related
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.
d3.json was working fine till I included this for loop in it. I am populating the patientList object which is basically a list of patient names, where each patient would have an array of appointment dates and alpha beta values. The database stores multiple rows for each patient where the name and alpha beta values remain same but dates vary. Therefore, this for loop is to sort out the info with name as primary key.But I have no idea what's wrong in here as it's my first time working with d3 and js.
var data;
var patientList = {};
d3.json("data.php", function(error, json) {
if (error) return console.warn(error);
data = json;
for(var i = 0; i < data.length; i++) {
var name = data[i].name;
if(!patientList[name]) {
var newPatient = {
dates: data[i].date,
alpha: data[i].alpha,
beta; data[i].beta
};
patientList[name] = newPatient;
} else {
patientList[name].dates.push(data[i].date);
}
}
alert("Hello," + data[3].name);
});
Any suggestions ??
Thanks in advance!
Maybe it's just the typo in
beta; data[i].beta
which should be
beta: data[i].beta
What does the console.log say?
this is my code, data grabs a json response from ajax.
when I do console.debug ...if you click on it to expand this is what it shows:
181818
0.10926253687316
303030
0.054454277286136
d8a890
0.091268436578171
d8d8d8
0.22377581120944
f0d8c0
0.3269616519174
and this my code:
data = $.parseJSON(JSON.stringify(a));
console.debug("Here is blah: %o", data);
var myArray = data;
alert(myArray);
for (var i=0, tot=myArray.length; i < tot; i++) {
console.log(myArray[i]); //"aa", "bb"
}
I am trying to loop through the array and log the pair to the console
something like : 181818 = 0.1092 etc..any ideas/suggestions please?
Something like
for (var key in data) {
console.log(key+" = "+data[key]);
}
Remember that data is an object not an array.
So in your php code you can just output an array like this
echo json_encode($someArray);
Where
$someArray[181818] = 0.10926253687316;
and so on.
Next you can modify as it according to your needs.
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.
I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
So I am trying to extract the contents using something like this:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
How should this be done?
Be careful, d is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
had same problem today, Your topic helped me so here goes solution ;)
alert(result.d[0].EmployeeTitle);
It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Here it is:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Sample JSON text:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
That should work. if not, then maybe you can give us a longer example of the JSON.
Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
This will work!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.
I have the following call:
$('#select_box_id').change(function() {
var action = $('#my_form').attr('action');
$.get(action,{},function(response){
$.each(response.result,function(i) {
alert("key is: " + i + ", val is: " + response.result[i]);
});
}, 'json');
});
The structure coming back from the server look like:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}