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.
Related
After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe
I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();
I am trying to map new values (from an external json file) into an array (array of arrays or KV pairs, generated from a php file query to mysql) in javascript/jQuery.
The structure of the array is:
"results":
[{"gender":"Male","DOB":"1993-09-22","location":"Main","procCode":"43653","preopDx1":"783.3","procedDate":"2008-06-02"},{"gender":"Female","DOB":"2001-11-07","location":"South","procCode":"11403","preopDx1":"216.5","procedDate":"2010-01-01"},...]
The json file looks like this:
[
{
"CPT": "10021",
"RVU": "1.27"
},
{
"CPT": "10022",
"RVU": "1.27"
}
]
The idea is to
a) Loop thru the myarray values and find each procCode
b) Match this procCode with the identical cpt code in the json file, and
c) Attach each new key/value pair to each 'row' of myarray
function addRVU (myarray, myjson){
var newObj = $.map(myarray, function (i,res){
if(myarray[i].procCode == myjson[i].CPT){
return myarray[i].RVU = myjson[i].RVU;
}
}
}
Thanks in advance!
// First, convert JSON file into an object keyed off CPT code:
var jsonObj = {};
for (var i = 0; i < json.length; i++) {
jsonObj[json[i].CPT] = json[i];
}
// Now update myarray elements
for (i = 0; i < myarray.length; i++) {
// $.extend copies properties from 2nd object into 1st object
$.extend(myarray[i], jsonObj[myarray[i].procCode]);
}
for if(myarray[i].procCode == myjson[i].CPT), you only matched the json and array with same index. loop to match all element in json should fix your problem.
or something like using a hash to map the RVU
h = {};
$.each(json, function(i, e){
h[e.CPT] = e.RVU;
});
$.each(ar, function(i, e){
e.RVU = h[e.procCode];
});
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.