Loop through Array and count - javascript

Been struggling with counting through this array. I was able to do it previously but I don't think I quite understand how the parameters of a function are assigned its data.
I am bringing in an array with from JSON data over AJAX, then using a .each loop to go through the data and count it. But I can't seem to count it when using the index parameter. It is just giving me the actual objects and not counting how many objects there are.
I was hoping that someone could help me understand why I am getting the object and not the count of objects in the array. What I have now is just my final attempt at getting it to count, I know it's wrong.
I am trying to count how many "results" there are in the array (that came from the JSON file).
I have added snippets of my code and attached a link to the JSON file. I have also marked the problem area with a comment saying Problem Area
CODE -
$.getJSON('http://api.fixer.io/latest?base=ZAR', {
action: "query",
list: "search",
format: "json",
}
, function (data) {
var baseCurr = data.base;
var baseDate = data.date;
$('#curr-cont').append('<div class="base row1" id="row1"><div class="base flag" id="flag"><i class="famfamfam-flag-za"></i></div><div class="base country-name"><p class="c-name" id="count-name">' + baseCurr + '</p></div><div class="base currency"><p class="c-amount" id="curr">' + baseDate + '</p></div></div>');
//***Problem Area***
var rates = [data];
$.each(rates[0], function (i, obj) {
console.log(obj);
});
$.each(data.rates, function (i, item) {
var amount = [item];
var name = [i];
var maxLength = 4;
var string = amount.toString();
string = string.substr(0, maxLength);
// amount = amount.substr(0, maxLength);
$('#curr-cont').append('<div class="row1" id="row1"><div class="flag" id="flag"><i class="famfamfam-flag-' + name + '"></i></div><div class="country-name"><p class="c-name" id="count-name">' + name + '</p></div><div class="currency"><p class="c-amount" id="curr">' + string + '</p></div></div>');
// if(i > 0){
// $('#list1').append('<li>' + name + '</li>');
// }
// else{
// $('#list2').append('<li>' + name + '</li>');
// }
});
});
JSON Data File

edit:
since rates is an object and not an array, you can do: Object.keys(data.rates).length.
Object.keys(...) will give you an array with all the keys in the object.
original:
If you want to know the number of rates in that file: data.rates.length will give you the length of the rates Array that is returned in the data.
No need to count it

Related

Javascript Multidimensional Array is Empty

I think Im misunderstanding something here - I normally work in PHP and think I'm missing something small. My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,". It seems to me my tmp array might be emptied somewhere or the scope gets reset for some reason. I'm using this as coordinates from a table where you can select table rows and posting to a webservice but my array seem to be erroneous.
var length = $("#arrayCount").html();
var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var col = getSelectedColumn(); //for example sake lets say "B" is the selected column
var row = getSelectedRow(); //selected rows will be from "11" - "16"
var columnIndexStart = letters.indexOf(col[0]);
var tmp = [];
for(var i = row[0]; i <= row[1]; i++) //rows[0] = 11 and rows[1] = 16
{
tmp[i] = [];
for(var j = columnIndexStart; j < letters.length; j++) //columns and starts at index 1 if we work with "B"
{
var val = $("#" + i + "_" + letters[j]).html(); //using the row and letters as the associated DOM elements ID. Easier to retrieve it's HTML then.
if(val != undefined)
{
console.log("Index [" + i + "]['" + letters[j] + "'] = " + val); //works perfectly and prints as it should.
tmp[i]['"'+letters[j]+'"'] = val; //using quotes to save letters? Is this preferred?
}
}
}
console.log('Final Array: ' + tmp); //empty??
console.log('Final Array: ' + tmp[14]['G']); //testing HTML output. But is undefined.
return tmp;
Any help will be greatly appreciated.
Edited:
Example of console output.
My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,"
With non-numeric index you are setting the field of object and not the element for index.
If you will have two-dimensional numeric array with numeric indices like the following:
var tmp = [[1,2,3], [1,2,3]];
after console.log('tmp = ' + tmp); you will obviously get the output string like:
tmp = 1,2,3,1,2,3
Because when you are trying to convert array to string it converts it elements to string and represent them with a commas.
However when you are trying to set element with non-numeric index, you are setting the field of this object.
var tmp = [];
tmp['A'] = 123;
console.log("tmp = " + tmp); // tmp =
console.log(tmp.A); //123
So, console.log in your case works good - it is serializing all elements of two-dimensional array. But no one array of the second level does not have stored values, it has only fields, which are not included in the string representation of array.
You are getting a set of commas, because each sub-array of tmp array does not contains any element, so it's string representation is an empty string. Each sub-array contains the required data into it's fields.
When you are performing sum operation of string and object you are forcing object to convert to string representation. Instead of this it is recommended to use console.log(yourObj) - it will log the whole object without converting it to string.
//using quotes to save letters? Is this preferred?
No, "A" and A are different identifiers.
var s = new Object();
s['"A"'] = 123;
console.log(s['A']); //undefined
console.log(s['"A"']); //123
Additionally, if you will set fields with quotes - you can not get the field in normal style:
console.log(s."A"); //syntax error : expected identifier after '.'
You can also just do this (use comma, not plus):
console.log('Final Array: ', tmp); //empty??
console.log('Final Array: ', tmp[14]['G']);

Javascript getting object properties

I want to create a google.Visualization.DataTablein the end, to show a graph. By now, I have a Problem with the following:
This is my code for getting Object from JSON-string and listing Properties:
var jsonData = <?php echo "'". $jsonTable. "'"; ?>;
var parsed = JSON.parse(jsonData);
var sensors = [];
for (var x in parsed){
sensors.push(parsed[x]);
}
var text ="";
for (var sensor in sensors){
if (sensors.hasOwnProperty(sensor)){
var measures = sensors[sensor];
text += ('\r\n' + sensor);
for (var time in measures){
if(measures.hasOwnProperty(time)){
text += ('\r\n' + time + " = " + measures[time]);
}
}
}
}
$(document.getElementById('chart_div')).text(text);
And my jsonData looks like this:
jsonData = '{"sensor1":
{"Date(2016,1,08,10,30,03)":19.187,
"Date(2016,1,08,10,00,02)":18.937[,...]},
"sensor2":
{"Date(2016,1,08,10,30,04)":18.687,
"Date(2016,1,08,10,00,03)":18.437[,...]}
[,...]}'
My Problem is that i don't get the values "sensor1", "sensor2" and so on in the loop. text += ('\r\n' + sensor); only returns the index of the sensor-object in the sensors-object.
How can I get the sensor name instead of the index?
One simple workaround
Remove the var sensors = [];
Find sensors and replace with parsed.
Code:
for (var sensor in parsed){
if (parsed.hasOwnProperty(sensor)){
var measures = parsed[sensor];
text += ('\r\n' + sensor);
console.log(parsed);
for (var time in measures){
if(measures.hasOwnProperty(time)){
text += ('\r\n' + time + " = " + measures[time]);
}
}
}
How can I get the sensor name instead of the index?
You need to do something with the property name in your first loop.
At present you are taking the property name (sensor1), using it to get the value ({"Date...) and then putting the value in an array while discarding the property name.
The simplest option would be to get rid of your first loop entirely and work with parsed instead of sensors in your second loop.

searching deeper than 1 into json

im trying to figure out how to search deeper than just one deep in my JSON file.
its structure is as follows
json>data>movies>
in movies the different movies are enumerated 0, 1, 2, 3, 4, etc so
json>data>movies>3>
would contain movie information for the 4th movie
each containing key value pairs.the code i am using only seems to look one deep, and i cant seem to get it to go deeper.
code is as follows
$('#search').keyup(function () { // i understand this to watch the form id search
var searchField = $('#search').val(); // sets variable searchfield from typed content, .val grabs the content
if (searchField.length) // this sets the length to false by default ensuring the code only runs when it is supposed to and not all the time
{
var myExp = new RegExp(searchField, "i"); // sets variable myexp to regular expression using "i" for case insensitive
var found = 0; // sets variable found to 0 to keep div hidden until match is found
$.getJSON('/secure/movies.json', function (data) { //gets movies.json file pushes to data function
var output = '<ul class="searchresults">';
$.each(data, function (key, val) { // this should make key pairs from data
if (val.title.search(myExp) !== -1) { // this is the problem i think
console.log(val); // this should show our search term results in console
found = 1;
output += '<li>';
output += '<h2>' + val.title + '</h2>';
output += "<a href=" + val.image + ' target="_blank" ></a>';
output += '</li>';
}
});
output += '</ul>';
if (found == 1) {
$('#update').removeClass('update-hidden');
$('#update').html(output);
} else {
$('#update').addClass('update-hidden');
}
});
} else {
$('#update').addClass('update-hidden');
}
});
ive tried manipulating val.title.search(myexp) but i might be missing the boat on whats happening here with val.title.search. thanks in advance

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

how to get random json data and append to div element

Say this is my json
[
{
"imageSmall": ["images/employee_jpgs/employees_abhishek_80x80.jpg"],
"imageBig": ["images/employee_jpgs/employees_abhishek_150x150.jpg"],
"name": ["Abhishek Shet"],
"quotes": ["Just perfect to start your career after school. Makes me feel others in the industry are way slower then us. Awesome team and and a brilliant product to work on!!!!. And most importantly I enjoy what I do :)."],
"type": "employee"
},
{
"imageSmall": ["images/employee_jpgs/employees_barbra_80x80.jpg"],
"imageBig": ["images/employee_jpgs/employees_barbra_150x150.jpg"],
"name": ["Barbra Gago"],
"quotes": ["The best part about working at tibbr is how dynamic the environment is, there's a lot of flexibility and freedom to execute on new ideas. Because everyone is so talented, there is a ton of trust and support coming from managers and team members-we all count on each other to do the best possible job!"],
"type": "employee"
},
the same continues but there are 3 types
1-employee
2-twitter
3-social
Now my problem is I want get these json data randomly and append to my div element
I used following code
function(args){
var me=this;
$.getJSON(args.json,function(data) {
me.set(args);
$.each(data, function(i){
var id="randomizr_item_" + i;
var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ this.imageSmall[0] +'" /></div>');
me.config.container.append(temp);
this.target=$(temp);
});
I know how to generate single random entry using following code
entry = data[Math.floor(Math.random()*data.length)];
which generates single random entry.
Plz help me how to get json data randomly from above json file and append to div.
You need to make an array of random unique numbers like following:
function generateRandom(min, max) {
var arr = [];
while(arr.length < 5){
var randNum = Math.floor(Math.random() * (max - min + 1)) + min,
found=false;
for(var i=0;i < arr.length; i++){
if(arr[i] == randNum){found=true;break}
}
if(!found)arr[arr.length] = randNum;
}
return arr;
}
Then you need to loop over data like following:
Here I am looping over unique array, not on data and using value of array as index to data.
var orders = generateRandom(0, data.length-1);
$.each(orders, function(index, value){
var id="randomizr_item_" + i;
var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ data[value].imageSmall[0] +'" /></div>');
me.config.container.append(temp);
this.target=$(temp);
});
A simple demo
You should create a 'Deck' and fill it with the json data.
Once the Deck is filled, loop through it while it has elements, like this:
while(deck.length > 0) {
var random_index = Math.floor(Math.random()*data.length);
var item = deck[random_index];
// do stuff with item
deck = jQuery.removeFromArray(random_index, deck);
}
Add this code to the top of your js file:
jQuery.removeFromArray = function(value, arr) {
return jQuery.grep(arr, function(elem, index) {
return elem !== value;
});
};

Categories