min & max of values in looped-thru JSON data (no jQuery) - javascript

In the following:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
} // processResponse
if (weighInData[obj].user === selUser) { ... returns the following (using example Ron):
Object { user="Ron", date="2014-08-01", weight="192"}
Object { user="Ron", date="2014-08-02", weight="195"}
Object { user="Ron", date="2014-08-03", weight="198"} ... etc.
... so my problem presently is where this belongs:
var peakWeight = Math.max.apply(Math, weights);
console.log("peakWeight: " + peakWeight);
Since I'm only after the weight values for the matching user, I assumed it would have to run within the 'if (weighInData[obj].user === selUser) { ... ', but this (and numerous other attempts in and out of the loop, including a for loop within the selUser) fail to achieve the desired results. In fact, even when the math function wasn't running on each value in 'weights', (i.e., outside the loop) and only ran outside the loop, the result was an incorrect value.
Any insight is greatly appreciated,
svs

Here's a very simple example you can probably adjust to fit your purpose:
// create this array outside of for loop so it already exists
var arr = [];
// test data
var a = { user:"Ron", date:"2014-08-01", weight:"192"};
var b = { user:"Ron", date:"2014-08-02", weight:"195"};
var c = { user:"Ron", date:"2014-08-03", weight:"198"};
// within for loop, you should only need to push once (per loop)
arr.push( a.weight );
arr.push( b.weight );
arr.push( c.weight );
// after the loop ends, display loop, get max and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
http://jsfiddle.net/biz79/sb7zayze/
If i were to edit your code, something like this might work:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
// ADDED: create array
var arr = [];
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
// ADDED: add to array
arr.push(weights);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
// ADDED: after the loop ends, display loop, get max/min and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
} // processResponse

Related

jQuery: Adding objects to arrays in each loops not working

I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);

Integer Arrays Passing To JavaScript Function

I have an array in php which i am getting in Javascript.
Here is my php code
$query = "SELECT SeatNum FROM `$busNum` WHERE AB = 1";
$runQuery = mysqli_query($con, $query);
$i = 0;
foreach($runQuery as $row)
{
$availableSeats[$i++] = $row['SeatNum'];
}
And here i am getting this string in javascript
var getBookedSeats = <?php echo json_encode($availableSeats); ?>;
var bookedSeats =[];
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = getBookedSeats[i];
}
The array also saved in bookedSeats successfully. Now the problem is that when i used that array as a parameter to call function. Nothing goes in the parameter. Even there is no problem of scope. This is my function looks like:
var init = function (reservedSeat) {
//code
}
init(bookedSeats);
Implementation of init function is :
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
Seems the problem is that you are trying to compare the array values as numbers and you currently have them as strings. To convert them to numbers, you can simply use:
bookedSeats = bookedSeats.map(Number) // iterate over each bookedSeats element and return its numeric value
Which is the same as:
bookedSeats = bookedSeats.map(function(value){
return Number(value);
})
From the comments it looks like your variable bookedSeats is being assigned with values. However, if your init() function is expecting integers, you'll want to build the bookedSeats array with integers like so:
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = parseInt( getBookedSeats[i], 10 );
}
I do not use php but I belive php's json_encode returns a JSON formatted string. Which results in your JavaScript code storing individual characters from the string into the bookSeats variable.
You need to parse the string returned from php. For example...
var getBookedSeats = JSON.parse(<?php echo json_encode($availableSeats); ?>);

How can I create methods for json objects in javascript?

I've created a quiz where every question is a Question object which question has methods like print quiestion and so on. I've added my questions inside the javascript file but I want to move the questions to an external Json file.
However I can't find any article that covers how two create methods for the imported Json objects (the question objects) in this case. Here is a piece of code for the quiz object with one method before using getJson:
$(function(){
// <-- QUESTION OBJECT -->
function Question(question, choices, correctChoice, userAnswer, type) {
this.question = question;
this.choices = choices;
this.correctChoice = correctChoice;
this.userAnswer = userAnswer;
this.type = type; // either radio buttons or check boxes
// <-- write question method -->
this.writeQuestion = function() {
var questionContent;
questionContent = "<p class='question'>" + (currentQue + 1) + ". " + this.question + "</p>";
var checked = "";
if(this.type === "radio") {
for(var i=0; i < this.choices.length; i++) {
if((i+1) == this.userAnswer)
checked = "checked='checked'";
questionContent += "<p><input class='css-radio' id='radio" + (i+1) + "' " + checked + " type='radio' name='choices' value='choice'></input>";
questionContent += "<label class='css-label' for='radio" + (i+1) + "'>" + this.choices[i] + "</label></p>";
checked = "";
}
}
else {
for(var i=0; i < this.choices.length; i++) {
if ((i+1) == this.userAnswer[i])
checked = "checked='checked'";
questionContent += "<p><input class='css-checkbox' id='checkbox" + (i+1) + "' " + checked + " type='checkbox' name='choices' value='choice'></input>";
questionContent += "<label class='css-label-checkbox' for='checkbox" + (i+1) + "'>" + this.choices[i] + "</label></p>";
checked = "";
}
}
return $quizContent.html(questionContent);
};
You should create a constructor function that receives the json and defines all methods there, using the json you've provided, something rough like this:
function Question(questionJson) {
var data = questionJson;
//Public "methods" are defined to "this"
this.getCorrectAnswer = function() {
return data.correctAnswer;
};
//Private "methods
var doSomethingCrazy = function() {
return "crazy";
};
this.getSomethingCrazy = function() {
return doSomethingCrazy();
};
}
And then, lets say you have an array of questions:
var questions = [
{questionId: '1', correctAnswer: 'a', possibleAnswers: []},
{questionId: '2', correctAnswer: 'a', possibleAnswers: []},
];
You do:
var instances = [];
for (var q in questions) {
instances[q.questionId] = new Question(q);
}
This code worked:
var allQuestions = [];
var category = "history";
for(var i=0; i < jsonDataLength; i++) {
allQuestions[i] = new Question(); // create empty question Obj
var questionNr = "q" + (i+1).toString(); // store questionNr in variable
for(var properties in jsonData[category][questionNr]) // loop through questionObjs properties
allQuestions[i][properties] = jsonData[category][questionNr][properties];
// add them to empty QuestionObj
}

javascript loop through json response

I want to loop through my json response. My json response looks like this
{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}
What I want is a foreach loop through all lines so i get the keys and the values for every line.
You could iterate like this: (added code-comments for explanation)
var result = document.getElementById("result");
var json = '{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}';
var obj = JSON.parse(json);
// json object contains two properties: "line" and "total".
// iterate "line" property (which is an array but that can be iterated)
for (var key in obj.line) {
// key here is the index of line array
result.innerHTML += "<br/>" + key + ": ";
// each element of line array is an object
// so we can iterate over its properties
for (var prop in obj.line[key]) {
// prop here is the property
// obj.line[key][prop] is the value at this index and for this prop
result.innerHTML += "<br/>" + prop + " = " + obj.line[key][prop];
}
}
// "total" is a property on the root object
result.innerHTML += "<br/><br/>Total = " + obj.total;
<p id="result"> </p>
Demo Fiddle: http://jsfiddle.net/abhitalks/ajgrLj0h/2/
.
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
for(var i = 0; i < json.line.length; i++)
{
console.log("Type: " + json.line[i].type + " Name: " + json.line[i].name + " Account: " + json.line[i].account + " Description: " + json.line[i].description + " Balance: " + json.line[i].balance + " Image: " + json.line[i].image);
}
You can do something like that...
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
if(json.line !== undefined && json.line.length > 0){
var key,value;
json.line.map(function(lineObject){
for (key in lineObject) {
value = (lineObject[key] == '')?'unknown': lineObject[key];
console.log(key+":"+ value);
}
console.log("---------------------");
});
}
http://jsfiddle.net/ddw7nx91/
var obj = {"line":[]} //your json here
for(var i=0; i<obj.line.length; i++) {
console.log(obj.line[i].type)
}
obj.line is an array, so you can get his length an cycle it.
This would create an array of lines each with a keys object and a values object.
var response = JSON.parse( {'your':'JSON'} );
var lines = [];
$.each( response, function( line ) {//loop through lines in response
var keys = [];
var values = [];
$.each( line, function( obj ) {
keys.push( Object.keys(obj) );//get keys
for( var key in obj ) {
values.push(obj[key]);//get values
}
});
lines.push({ {'keys':keys},{'values':values} });
});

javascript post items array variable

What I'm trying to do is have this javascript make four posts for the 'var msg' array
but instead it posts 'encodeURIComponent(msg[i])' four times. How do I fix this?
var msg = ['one',
'two',
'three',
'four' ];
for (var i in msg) {
var post_form_id = document['getElementsByName']('post_form_id')[0]['value'];
var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/profile/composer.php?__a=1';
var paramswp = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u3bbpq_21&xhpc_targetid=' + 254802014571798 + '&xhpc_context=profile&xhpc_location=&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=1&xhpc_message_text=" + encodeURIComponent(msg[i]) + "&xhpc_message=" + encodeURIComponent(msg[i]) + "&aktion=post&app_id=2309869772&attachment[params][0]=254802014571798&attachment[type]=18&composertags_place=&composertags_place_name=&composer_predicted_city=102186159822587&composer_session_id=1320586865&is_explicit_place=&audience[0][value]=80&composertags_city=&disable_location_sharing=false&nctr[_mod]=pagelet_wall&lsd&post_form_id_source=AsyncRequest&__user=' + user_id + '';
{
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['send'](paramswp);
i += 1;
}
}
At this point you are switching from single to double quotes:
&xhpc_message_text=" + encodeURIComponent(msg[i]) + "&xhpc_message=" + encodeURIComponent(msg[i]) + "&aktion=post&app_id=2309869772
Try using single quotes instead, and it should be parsed correctly.
Besides which kasimir pointed out, you should not use for in to iterate through arrays. Change your code to for (var i = 0, nMsg = msg.length; i < nMsg; ++i) and remove line i = i + 1

Categories