Javascript: Each Array - javascript

Note: No jQuery
How could i do something like this:
var array = new Array();
array[name] = "Tom";
array[age] = 15;
foreach(array as key=>value){
alert(key + " = " + value);
}

First of all, you should call it obj or person instead of array; an array is a sequence of similar elements, not a single object.
You can do it like this:
var person = new Object();
person['name'] = "Tom";
person['age'] = 15;
for (var key in person) {
if(!person.hasOwnProperty(key)) continue; //Skip base props like toString
alert(key + " = " + person[key]);
}
You can also initialize the object using properties, like this:
person.name = "Tom";
person.age = 15;
You can also use JavaScript object literal syntax:
var person = { name: "Tom", age: 15 };

This will work in your simple example scenario:
for (var key in array) {
alert(key + " = " + array[key]);
}
For general use, it's recommended that you test to be sure that the property hasn't been grafted onto the object somewhere else in the inheritance chain:
for (var key in array) {
if (array.hasOwnProperty(key)) {
alert(key + " = " + array[key]);
}
}

Use a javascript object
var object = {};
object.name = "Tom";
object.age = 15;
for ( var i in object ) {
console.log(i+' = '+ object[i]);
}

First, you don't want an array, you want an object. PHP's idea of what constitutes an array is frankly a little weird.
var stuff = {
name: "Tom",
age: 15
};
/* Note: you could also have done
var stuff = {};
stuff.name = "Tom";
stuff.age = 15;
// or
var stuff = {};
stuff["name"] = "Tom";
stuff["age"] = 15;
*/
for (var key in stuff) {
alert(key + " = " + stuff[key];
}

key=0;while(key<array.length) {
alert(key + " = " + array.item(key));
key++;
}

Related

generate varname in jquery

In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data

javascript print nested object using for loop?

how do i print out all the person in the person object?
For Example i want my output to be like this.
John Doe 25
Paul Vosper 23
var txt = "";
var person = {
p1: {fname:"John", lname:"Doe", age:25},
p2: {fname:"Paul", lname:"Vosper", age:23}
};
var x;
for (x in person)
{
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
You can do a map/join:
var txt = Object.keys(person).map(function(k) {
var p = person[k];
return [p.fname, p.lname, p.age].join(' ');
}).join(' ');
Output in the console:
If you want a line break element (<br>) between them, just join on a <br>:
document.getElementById("demo").innerHTML = Object.keys(person)
.map(combineAllProperties)
.join('<br>');
function combineAllProperties(k) {
var p = person[k];
return [p.fname, p.lname, p.age].join(' ');
}
You can use Array.prototype.reduce in conjunction with Object.keys:
var person = {
p1: {fname:"John", lname:"Doe", age:25},
p2: {fname:"Paul", lname:"Vosper", age:23}
};
document.write(Object.keys(person).reduce(function(s, p, i) {
var o = person[p];
return s + (i>0?'<br>':'') + o.fname + ' ' + o.lname + ' ' + o.age
}, '')
);

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} });
});

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

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

Categories