How do I loop through a JSON list? - javascript

I have multiple items in my JSON list. I want to loop through it and display it on my page. I can't seem to get to the next object though.
{
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}],
"room2":[
{"campusName":"C",
"buildingCode":"D",
"roomNumber":"208",
"times":["7-8", "9-10"
]}
]}
$(document).ready(function(){
$.getJSON("data.json", function(data){
$.each(data.room, function(){
for(var i = 0; i < data.length; i++){
$("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>");
}
});
});
});

Try this
var list = '';
$.each(data, function (i, root) {
$.each(root, function (i, el) {
list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>";
});
});
$('ul').html(list);
Example
If root's has only one element in array
var list = '';
$.each(data, function (i, root) {
list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>";
});
$('ul').html(list);
Example

$.each(data, ..) --> Each element will be:
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}]
Then, this[0] will provide the object you need to construct your li:
$.each(data, function(){
$("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>");
});
Fiddle

Related

Jquery + $.each + dynamic operation + using parameters

function Controles(contro, nomtab, numtab, action, nomcla, tipdat, lista, datos) {
$(document).on('click', '.'+contro+' #IZQTOD', function(event) {
$.getJSON(action+'&rows='+rows+'&page=1', function(datos) {
var nuevafila;
$.each(datos+tipdat, function(index, data) {
nuevafila = nuevafila + "<tr class='Fila-Grid-"+nomcla+"' id='" + numtab + (index + 1) + "'>";
nuevafila = nuevafila + "<td class='Columna1'>" + (index + 1) + "</td>";
var list = lista.split("-");
for (var j = 1; j < list.length; j++) {
nuevafila = nuevafila + "<td class='Borde-'>" + data+list[j] + "</td>";
}
nuevafila = nuevafila + "</tr>";
});
$('#'+nomtab+' tr:eq(1)').after(nuevafila);
});
});
}
I want to run this piece of code as a function of javascript in order to reuse code.
The part that does not work for me is the part of each:
   $. each (+ tipdat data, function (index, data) {
Where "datos" is an object with variables (set and get) (codcli, name, apepat)
I mean to call codcli I do:
   $. each (datos.codcli, function (index, data) {
}
But this way is static. I want to do through dynamic parameters.
So the question is how to pass parameters to successfully achieve? Or is that you can not do? There will always be static?
in the code above what I want to do is, but obviously does not work:
tipdat=".codcli"
   $. each (datos+tipdat, function (index, data) {
}
I think you're looking for bracket notation.
var tipdat = "codcli";
$.each(datos[tipdat], function (index, data) {
//...
});
Is the same as:
$.each(datos.codcli, ...
If your string has multiple properties, I would do something like this:
var tipdat = "codcli.cod";
var objToIterate = datos;
var parts = tipdate.split('.');
for(var i = 0; i< parts.length; i++) {
objToIterate = objToIterate[parts[i]];
}
$.each(objToIterate, function (index, data) {
//...
});

remove array using jquery

I have created nestled arrays, which I then append to a div. When i click the button with id "name", a movie with title is stored in an array $titelBetyg, which is later stored in another array $films. Whenever i create a new $titelBetyg, i want to remove the previous $films from my div, before replacing it with the new one. How do I do this?
Javascript
$(document).ready(function(){
var $films = [];
$('#name').keyup(function(){
$('#name').css('background-color', 'white');
});
$('#options').change(function(){
$('#options').css('background-color', 'white');
});
$("#button").click(function(){
var $titelBetyg = [];
var $titel = $('#name').val();
var $betyg = $('#options').val();
if($titel == ""){
$('#name').css('background-color', 'red');
alert("Fail");
}
else if($betyg == "0"){
$('#options').css('background-color', 'red');
alert("Fail");
}
else{
$titelBetyg.push($titel);
$titelBetyg.push($betyg);
$films.push($titelBetyg);
// here is where i need to remove it before appending the new one
$('#rightbar').append("<ul>");
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");
}
});
$('#stigande').click(function(a,b){
});
$('#fallande').click(function(){
});
});
Use .empty() like this (and append to the <ul> instead of something else):
var $ul = $("<ul>");
for (var i=0; i<$films.length; i++) {
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li><br>");
}
$('#rightbar').empty().append($ul);
Btw, it might be easier to only append the new one instead of emptying and rebuilding the whole thing:
$('#rightbar ul').append("<li>" + $titel + " " + $betyg + "</li><br>");
To remove only the list contents (and nothing else) from the #rightbar, you could use this:
var $ul = $('#rightbar ul').empty();
if (!$ul.length) // if nonexistent…
$ul = $("<ul>").appendTo('#rightbar'); // create new one
for (var i=0; i<$films.length; i++)
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>");
document.getElementById('rightbar').innerHTML = '';
That way rightbar is totally empty.
You only require to remove the content of the container. So, use the .empty() function
$('#rightbar').empty().append("<ul>"); //It will empty the content and then append
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");

Assign Nested JSON to li using jquery

I am trying to parse a json file using jquery getJson. I have no problem looping through the first layer, but I need to assign a nested array to li as well.
My JSON Code
{"Controls":[
{
"Object":"Button",
"ButtonAttr": [{"x": "1","y": "2","width": "3","height": "4"}]
},
{
"Object":"Image",
"ButtonAttr": [{"x": "5","y": "6","width": "7","height": "8"}]
},
{
"Object":"TextField",
"ButtonAttr": [{"x": "9","y": "10","width": "11","height": "12"}]
}
]}
My JS/JQUERY Code where I have no problem bringing in the first layer of the JSON and appending it to a li. I need to figure out how to get the 'ButtonAttr' layer
//Get JSON File which contains all Controls
$.getJSON('controls.json', function(data) {
//Build Objects List
var objectList="<ul>";
for (var i in data.Controls) {
objectList+="<li>" + data.Controls[i].Object +"</li>";
}
objectList+="</ul>";
$('#options').append(objectList);
//Add new Code Object based on #Options LI Index
$(document).on('click','#options li', function() {
var index = $('#options li').index(this);
$('#code').append('<li>' + data.Controls[index].Object + '</li>');
//Shows Selected LI Index
$('#optionsIndex').text("That was div index #" + index);
});
});
I cannot for the life of me get it to loop through the second array and list out the x,y,width, and height fields.
Here is my desired output
<ul>
<li>Button</li>
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
<li>Image</li>
<ul>
<li>x:5</li>
<li>y:6</li>
<li>width:7</li>
<li>height:8</li>
</ul>
<li>TextField</li>
<ul>
<li>x:9</li>
<li>y:10</li>
<li>width:11</li>
<li>height:12</li>
</ul>
</ul>
Any help would be greatly appreciated
I worked through this in another question.
How to handle comma separated objects in json? ( [object Object],[object Object] )
You want a recursive function that starts a <ul> and adds <li> for each item in the list. It also tests items, and if they are themselves lists, it calls itself with that piece of data as the argument. Each time the function is called from within the function you get a <ul> within a <ul>.
function buildULfromOBJ(obj){
var fragments = [];
//declare recursion function
function recurse(item){
fragments.push('<ul>'); // start a new <ul>
$.each(item, function(key, val) { // iterate through items.
if((val != null) && (typeof val == 'object') && // catch nested objects
((val == '[object Object]') || (val[0] == '[object Object]'))){
fragments.push('<li>[' + key + '] =></li>'); // add '[key] =>'
recurse(val); // call recurse to add a nested <ul>
}else if(typeof(val)=='string'){ // catch strings, add double quotes
fragments.push('<li>[' + key + '] = \"' + val + '\"</li>');
}else if($.isArray(val)){ // catch arrays add [brackets]
fragments.push('<li>[' + key + '] = [' + val + ']</li>');
}else{ // default: just print it.
fragments.push('<li>[' + key + '] = ' + val + '</li>');
}
});
fragments.push('</ul>'); // close </ul>
}
// end recursion function
recurse(obj); // call recursion
return fragments.join(''); // return results
} // end buildULfromOBJ()
save your self the pain of trying to do with with for loops etc. and use client-side templating like json2html.com
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='http://json2html.com/js/jquery.json2html-3.1-min.js'></script>
<ul id='out'></ul>
<script>
var data =
{"Controls":[
{
"Object":"Button",
"ButtonAttr": [{"x": "1","y": "2","width": "3","height": "4"}]
},
{
"Object":"Image",
"ButtonAttr": [{"x": "5","y": "6","width": "7","height": "8"}]
},
{
"Object":"TextField",
"ButtonAttr": [{"x": "9","y": "10","width": "11","height": "12"}]
}
]};
var template = {"tag":"li","children":[
{"tag":"span","html":"${Object}"},
{"tag":"ul","children":[
{"tag":"li","html":"x: ${ButtonAttr.0.x}"},
{"tag":"li","html":"y: ${ButtonAttr.0.y}"},
{"tag":"li","html":"width: ${ButtonAttr.0.width}"},
{"tag":"li","html":"height: ${ButtonAttr.0.height}"}
]}
]};
$('#out').json2html(data.Controls,template);
</script>
You can do it like this.. using the $.each and a for in loop
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + v.Object + '</li><ul>';
for(var kk in v.ButtonAttr[0]){
str += '<li>' + kk + ':' + v.ButtonAttr[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
FIDDLE
or with 2 $.each loops
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + v.Object + '</li><ul>';
$.each(v.ButtonAttr[0],function(kk,vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul>';
});
str += '</ul>';
FIDDLE
You can loop through the second array just as easily as the first, like so:
$(document).on('click','#options li', function() {
var index = $('#options li').index(this);
$('#code').append('<li>' + data.Controls[index].Object + '</li>');
// Create a new sub-UL to after the LI
var $subUl = $(('<ul>')
// Iterate through each attribute in ButtonAttr
$.each(data.Controls[index].ButtonAttr, function(key, value){
// Append a new LI with that attribute's key/value
$subUl.append('<li>' + key + ':' + value + '</li>');
});
// Append that new sub-UL we made after the last LI we made
$('#code li:last').after($subUl);
//Shows Selected LI Index
$('#optionsIndex').text("That was div index #" + index);
});

Getting index number of element of array

I have json with array of objects in it. I build my page depends on elements in this array. If there is no duplicate values of key called points, i render page with some info and description, using value of points to find this element in array. However if i have 2 and more duplicate values of key called points i render list of these elements. In this case i cant use value of points to find element in array. I know i can use index number of array element, and then pass it as parameter to my function that find and build info and description, but i'm not sure how to do that. How do i get index number of element in array?
P.S. Can provide my code if needed
Code that i'm using
var allRewards = null;
$("#reward").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/test.json"
dataType: "json",
error: function (data, textStatus){
console.log( "it`s error" );
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var arr = [];
var iter = 0;
allRewards = data
$.each(data.rewards, function(key, val){
if ($.inArray(val.points, arr) == -1)
{
lis += "<div data-points='"+ val.points +"'align=CENTER class = 'rewards-block ui-block-" + String.fromCharCode(97 + iter%3) + "'><a href ='#' class ='ui-link-inherit' onclick='showreward("+val.points+")'><img src ='./img/reward-icon.png'/><span>" + val.points + " pts</span></a></div>";
arr.push(val.points);
iter += 1;
}
});
$("#rewards_table").html(lis);
})
});
function showreward(point)
{
$.mobile.changePage('show-rewards.html')
console.log(allRewards);
$("#showrewards").live('pagecreate', function(e) {
var items = "";
var arr = [];
var counter = 0;
var result = $.grep(allRewards.rewards, function(e){ return e.points == point; });
if (result.length > 1)
{
$.each(result, function(key, val){
items += "<div style='color:white;'>" + val.title + "</div>"
console.log(val.title);
})
}
else if (result.length == 1)
{
// $.each(result, function(key, val){
// items += "div style='color:white;'"+ val.points + "></div>"
// console.log(val.points);
// })
$.each(result, function(key, val){
items += "<div style='background:white; padding:5px 5px 20px 5px;'><img style ='float:right; width:45%; margin-top:22px; padding: 0 0 10px 10px;' src ='" + val.main_photo_url + "'/><h3>"+ val.title + "</h3><p>" + val.description + "</p><p style='font-weight:bold; font-size:13px;'>Reedem below for " + val.points + " Zingle Points</p><table class='pagemenu' style='width:200px;'><tr><td class='width_5'><input type='submit' data-theme='w' value='Reedem Now' data-inline='true'></td><td><a data-role='button' data-icon='pagemenu-share' data-iconpos='notext' href='index.html' data-shadow='false' data-corners='false'></a></td></tr></table></div>"
});
}
console.log(items);
$("#rewards-list").html(items);
});
}
I think you're looking for Array.indexOf.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
PS. This is available in Underscore as _.indexOf.

Iterating a JSON return properly

I have a strange problem with my script. I am getting a JSON result set and want to iterate it and then display in a div. I checked fiddler and I can see the entire set being returned like the set below
[{"EPubID":71,"SerialID":1,"PartnerID":343,"Partner":"Aberdeen, City of ","PublicationTitle":"Uploading multiple files test","AuthFirstName":null,"AuthMiddleName":null,"AuthLastName":null,"AuthFullName":null,"PublicationYear":2011,"SubmitterEmail":null,"VolumeNumber":null,"Issue":null,"AlreadyInCatalog":false,"InCatalog":"No","Status":"D","Notes":"testing multiple file uploads","IsMonograph":false,"Monographed":"No","SubmittedDate":"\/Date(1317913458810)\/","SubmittedBy":"admin","ApprovedDate":"\/Date(1317914842263)\/","ApprovedBy":"admin","SubmittingPartnerID":0,"OriginalRefId":"343-71","SerialName":"None","URL":null,"InfoRecordID":0,"LastModified":"\/Date(-62135568000000)\/","IsSerial":false,"Approved":false,"Delete":false,"Pending":false,"files":null},{"EPubID":72,"SerialID":19,"PartnerID":26,"Partner":"Digital Archives","PublicationTitle":"testing multiple file uploads ","AuthFirstName":null,"AuthMiddleName":null,"AuthLastName":null,"AuthFullName":null,"PublicationYear":2001,"SubmitterEmail":null,"VolumeNumber":"1","Issue":"1","AlreadyInCatalog":false,"InCatalog":"No","Status":"A","Notes":"this should work","IsMonograph":false,"Monographed":"No","SubmittedDate":"\/Date(1317915134767)\/","SubmittedBy":"admin","ApprovedDate":"\/Date(1317915430627)\/","ApprovedBy":"admin","SubmittingPartnerID":0,"OriginalRefId":"26-72","SerialName":"Fake Test Serial","URL":null,"InfoRecordID":0,"LastModified":"\/Date(-62135568000000)\/","IsSerial":false,"Approved":false,"Delete":false,"Pending":false,"files":null}]
The problem is my script is only displaying the first item returned and nothing else. Here is my script.
function SearchExistingEpubs() {
var title = $("input#PublicationTitle").val();
$('#Results').hide();
$("div#SearchResults").innerHTML = '';
$.getJSON('/EPub/SearchExistingEpubs/' + title, null, function (data) {
var items = [];
var found = false;
$.each(data, function (key, val) {
found = true;
$("div#SearchResults").empty();
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear) ;
$('#Results').show();
});
if (!found) {
$("div#SearchResults").empty();
//$("div#SearchResults").html('');
$("div#SearchResults").append("No documents found");
$('#Results').show();
//$('#Results').slideUp(10000);
$('#Results').animate({height:'toggle'},10000);
//$('#Results').fadeOut(10000);
}
//$('#Results').show();
});
};
You're wiping out the contents of the div in each iteration of the loop with your call to empty():
$.each(data, function (key, val) {
found = true;
$("div#SearchResults").empty(); // <------ REMOVE this line
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear) ;
$('#Results').show();
});
But doing dom updates in a loop is not usually a good idea. Why not build up your string and do one dom update:
var content = '';
$.each(data, function (key, val) {
found = true;
content += "Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear;
});
$("div#SearchResults").append(content);
$('#Results').show();
In your .each loop you're calling $("div#SearchResults").empty(); this will clear any content you've previously appended to this div.
Try the following:
function SearchExistingEpubs() {
var title = $("input#PublicationTitle").val();
$('#Results').hide();
$("div#SearchResults").empty();
$.getJSON('/EPub/SearchExistingEpubs/' + title, null, function (data) {
$("div#SearchResults").empty();
var items = [];
if (data.length) {
$.each(data, function (key, val) {
$("div#SearchResults").append("Title: " + val.PublicationTitle + " Owning Partner: " + val.Partner + " Year: " + val.PublicationYear);
});
$('#Results').show();
} else {
$("div#SearchResults").append("No documents found");
$('#Results').show();
$('#Results').animate({height:'toggle'},10000);
}
});
};

Categories

Resources