jQuery loop through JSON array - javascript

I have a json array which i fetch by a ajax call and would like to loop through it.
The array outputs a category titel and some data records within that category.
The array is as followed:
{"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]}
The basic each function like so can't help me.
$.each(data, function(key, value) {
console.log(value.title);
}
I want to be able to output it with the main category title and under that have the data records shown.
So for example i want it to look like this:
Travel (3 results):
Beautiful title 1
Beautiful title 2
Beautiful title 3
List item
Other (1 results):
Beautiful title 1
Any help would be greatly appreciated. Thank you.

var data = {"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]};
$.each(data, function (key, value) {
$('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
var list = $('<ul></ul>');
$('body').append(list);
$.each(value, function (index, titleObj) {
list.append('<li>' + titleObj.title + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

You would need nested .each() as the array contains nested objects.
$.each(data,function(i,object){
console.log(i +'('+object.length+')')
$.each(object, function (index, obj) {
console.log(obj.title);
});
});
Fiddle

Try
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
var data = {
"Travel": [{
"title": "Beautiful title 1"
}, {
"title": "Beautiful title 2"
}, {
"title": "Beautiful title 3"
}],
"Other": [{
"title": "Beautiful title 1"
}]
};
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Actually you have a Travel key their
So you can do it like :
$.each(data.Travel,function(key, value){
console.log(value.title);
}

Related

Creating a UL populated with the keys and values of a JSON with jQuery

What I have is this.
The HTML
<div id="catcher"></div>
The jQuery
jQuery.ajax({
url:'./ajax.html',
async: true,
success: function(response){
for (var key in response){
jQuery('#catcher')
.append("<ul>"+ key +"<li>" + response[key].toString() + "</li></ul>");
}
}
})
The JSON looks like
{
"Item":"Item Name",
"Item 1":"Item Name",
"Item 2":"Item Name",
"Item 3":"Item Name",
"Item 4":"Item Name"
}
I would like to make a UL like this
Item
Item Name
Item 1
Item Name
And so on.
What I am getting now is each individual letter of the value of the object and a numbers for the key. Instead I want them both to be equal to the strings.
You should try to add console.log(response) to your success callback. It will probably show that response is a string and not an object.
In this case you can add dataType:'json' to the jQuery.ajax(...) call, as explained here : how to parse json data with jquery / javascript?
You're missing an outer ordered-list. If you append that first and change your looped append to have a nested <ul> you should get the structure you're looking for:
var data = {
"Item": "Item Name",
"Item 1": "Item Name",
"Item 2": "Item Name",
"Item 3": "Item Name",
"Item 4": "Item Name"
}
$('#catcher').append('<ol></ol>');
for (var key in data) {
$('#catcher ol').append('<li>' + key + '<ul><li>' + data[key] + '</li></ul></li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="catcher"></div>
Try out this code. See if it helps:
jQuery.ajax({url:'./ajax.html', async: true, success: function(response){
var addcode=" ";
var i=1;
$.each(response, function(key,value) {
addcode += '<ul>' + (i++) + '. ' + key;
addcode += '<li>' + value + '</li>';
addcode += '</ul>';
});
jQuery('#catcher').html(addcode);
}})
jQuery.ajax({
url: './ajax.html',
async: true,
success: function(response) {
var ol = "<ol>";
for (var key in response) {
ol += "<li>" + key + "<ul><li>" + response[key] + "</li></ul>" + "</li>";
}
ol += "<ol>";
jQuery('#catcher').append(ol);
}
});
Try below code, Below code sample is used to loop only json attributes.
$.each( response, function( key, value ) {
alert( key + ": " + value );
});

How to read array from html to js

I declare an array with json data, then when I init the array should be read and display on the div.
But now show nothing, can anyone help me check my code, what mistake I have made. Thanks.
JS Fiddle
HTML
<script>
$(function() {
var array = [];
array[0] = {
"no": "1",
"name": "fruit",
"value": "mango",
"totalvote": "75"
};
array[1] = {
"no": "2",
"name": "fruit",
"value": "apple",
"totalvote": "10"
};
array[2] = {
"no": "3",
"name": "fruit",
"value": "orange",
"totalvote": "5"
};
array[3] = {
"no": "4",
"name": "fruit",
"value": "banana",
"totalvote": "45"
};
PG.init("popup_survey_whitebox_selection", "1", array);
PG.callpopup();
PG.render_1();
});
</script>
JS
var PG = {
divid: "",
multiselection: "",
optionitem: [],
/* type:"", */
init: function (divid, multiselection, optionitem) {
/* PG.type = type;*/
PG.divid = divid;
PG.multiselect = multiselection;
PG.optionitem = optionitem;
},
test: function () {
for (var i = 0; PG.optionitem.length > i; i++) {
alert(PG.optionitem[i].name);
}
},
callpopup: function () {
$("#popup_survey_whitebox_content").hide();
var orig = '', // create var to cache the original text
newText = ''; // create var to cache the new Text with "..."
$("label#popup_survey_label_title").text(function (index, currentText) {
orig = currentText;
newText = currentText.substr(0, 30);
if (currentText.length > 30) newText += "...";
return newText;
});
$("#popup_survey_whitebox").hover(function () {
$('#popup_survey_whitebox_content').stop().animate({
opacity: 1,
height: "toggle"
}, 500, function () {
$("label#popup_survey_label_title").text(orig); // Here put the original text.
}).css('position', 'relative');
}, function () {
$('#popup_survey_whitebox_content').stop().animate({
opacity: 1,
height: "toggle"
}, 500, function () {
$("label#popup_survey_label_title").text(newText); // Here put the new text with "..."
}).css('position', 'relative');
});
$("#popup_survey_end_whitebox").click(function () {
$("#popup_survey_whitebox").remove();
});
},
render_1: function () {
$.each(array, function (i, obj) {
if (PG.multiselect == 1) {
var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='radio' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
"<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
"</div></div>" +
"<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
} else {
var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='checkbox' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
"<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
"<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
"</div></div>" +
"<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
}
$("#" + PG.divid).append(selection);
});
var survey_button = "<br><input id='submit_btn' type='button' class='whiteboxbutton whiteboxbutton-small' value='Finish' style='width:100%;'>";
$("#popup_survey_label_title").append("What is your favorite fruit??What is your favorite fruit??");
/*$("#popup_survey_whitebox_title").append();*/
$("#popup_survey_whitebox_inner_title").append("Please select 1 fruit only:");
$('#popup_survey_whitebox_button').append(survey_button);
$('.the_checkbox').on('change', function (evt) {
$('.popup_survey_whitebox_percent').css('display', 'block');
$('.popup_survey_whitebox_progressbar').css('display', 'block');
$(".popup_survey_whitebox_button").show();
if ($(this).siblings(':checked').length >= PG.multiselect) {
this.checked = false;
}
});
},
save: function () {}
}
I console and get this error Uncaught ReferenceError: array is not defined but I must declare on html.
There is other way around as well to solve this error besides closure. Since, you already have optionitem present in PG and you already passed the optionitem to it, you can use it as well inside render_1 method.
Change
$.each(array, function (i, obj) {
to
$.each(PG.optionitem, function (i, obj) {
With that, you need not to define array as a global variable which might conflict with others.
http://jsfiddle.net/5qnhcudp/2/
Your array is in a closure. There is a couple of different things you could do but simply, you can just move your array declaration outside of the closure.
JSFiddle
<script>
var array = [];
$(function() {
...
});
</script>
Found another solution to your problem, your PG object is actually trying to reference the global scope where it doesn't need to. See, your inline script where you declare the array, you are passing that into the PG object.
You have this:
render_1: function () {
$.each(array, function (i, obj) {
...
});
}
Replace with this:
render_1: function () {
$.each(PG.optionitem, function (i, obj) {
...
});
}
This solution is actually independant from my first one. If you don't want the array in global scope, this solution will work.

JSON multi-value

i need help parsing the following:
{
"data": [
{
"Function": "Administration",
"SubFunction": "Facilities,Maintnce,Bldg Svcs,Other,Secretary"
},
{
"Function": "Communications",
"SubFunction": "Internal Communications,Marketing Comm,Other"
},
{
"Function": "Customer_Services",
"SubFunction": "Customer Engineer,Dispatcher,NonQuota Acct Supp Mgr,Other,PreSales-Network,Process and Systems,Quota Acct Supp Mgr,Remote Support Services,Rework,Service Offer Development,Services Logistics,Services Planning,Technology Consultant"
}
]
}
My jQuery code is:
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$.each(this.SubFunction, function(){
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
})
})
What should happen: The first option box should be filled with the "Function" and the second with the "SubFunction" upon the "Function" selection.
What is happening: The first option box does load up the "Function" values correctly, but the second drop down has all of the "Subfunction" from all "Function" with multiple instances of them.
Please help.
Thank You.
You need a change handler for this. This should do the job:
$select3 = $('#select3');
$select4 = $('#select4');
$.each(data.data, function() {
addOption($select3, this.Function);
});
$.each(data.data[0].SubFunction.split(','), function() {
addOption($select4, this);
});
$select3.on('change', function() {
$select4.html('');
$.each(data.data, function() {
if ($select3.val() === this.Function) {
$.each(this.SubFunction.split(','), function() {
addOption($select4, this);
});
}
});
});
function addOption($target, value) {
$target.append('<option id="' + value + '">' + value + '</option>');
}
http://jsfiddle.net/m88u76eL/
DEMO
Here is how to do it. You could use a data attribute to store the options for each function in the the option elements of select3, then when each of these options is selected, the value in the data attribute is read and parsed and used to populate select4 on-the-fly.
$select3.empty();
$.each(data.data, function(key, val){
$select3.append(
$('<option/>',{id:val.Function,text:val.Function,'data-sub-function':val.SubFunction})
);
});
$(function() {
$select3.on('change',function() {
$select4.empty();
$.each($('option:selected', this).data('sub-function').split(','), function(i,val){
$select4.append(
$('<option/>', {id:val,text:val})
);
});
})
.change();
});
You are already looping in data Object why are you doing a extra $.each ?
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
});
This just work just find? Not tested tho just a quick post to help out

Parse Json Array in jQuery

I am new to jQuery and Java script. I need to parse a JSON file that has arrays, I use this code:
$.getJSON('mat.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {'class': 'my-new-list', html: items.join('')}).appendTo('body');
});
For this JSON file:
{
"#file_name": "materials",
"materials": [{
"#site_name_English": "N/A",
"#site_name_Spanish": "N/A",
"#site_number": "1",
"zoom": [{
"#zoom_name_English": "Main Reservoir",
"#zoom_name_Spanish": "DepĆ³sito principal",
"#zoom_number": "1",
"icon": [
{
"#icon_name": "Info Icon 1",
"#icon_pin": "1"
},
{
"#icon_name": "Info Icon 2",
"#icon_pin": "2"
}
]
}]
}]
}
But my result is:
materials
[object Object]
How can I change my code so I will get the objects also when the loop meets them?
Use this:
$.each(data, function(key, val)
{
if(typeof val === 'object') {
$.each(val, function(keys, value)
{
items.push('<li id="' + keys + '">' + value + '</li>');
}
} else {
items.push('<li id="' + key + '">' + val + '</li>');
}
});
You need to check that value is object or not.
EDITED:
function checkObj(key, val, items){
if(typeof val === 'object') {
$.each(val, function(keys, value)
{
if(typeof value === 'object') {
checkObj(keys, value, items);
} else {
items.push('<li id="' + keys + '">' + value + '</li>');
}
});
}
}
And in the $.each function use this:
$.each(data, function(key, val)
{
if(typeof val === 'object') {
checkObj(key, val, items);
} else {
items.push('<li id="' + key + '">' + val + '</li>');
}
});
The program shows how to read json and store data into textbox
$(document).ready(function(){
$.getJSON("Test.json",function(data){
$.each(data,function(key,value){
alert(data[key].attrib1name);
alert(data[key].attrib2name);
$('input').val(data[key].enterpriseName);
activities=data[key].activities;
console.log(value);
});
});
});

Why is jquery.each executing twice?

JSFiddle here: http://jsfiddle.net/xgTt2/3/
I have a $.each nested inside of a $.each, and I'm not sure why the second $.each is running twice. Any ideas?
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
$('#placeholder').append('<p>' + pos.Id + '</p>')
$.each(pos.OrderItems, function (index) {
$('.orderitem').append('<p>' + this.Id +
' ' + this.Description + '</p>')
});
});
The above javascript is producing the following output:
aaa
1 Salad
2 Pizza
3 Salad
4 Pizza
bbb
3 Salad
4 Pizza
I want this:
aaa
1 Salad
2 Pizza
bbb
3 Salad
4 Pizza
Any idea what I'm doing wrong? Here's a working example of the problem: http://jsfiddle.net/xgTt2/3/
Near the end, you have two elements with the class orderitem. Using $('.orderitem').append() will append to both of them.
Instead, you want to append to the last element you created.
var $order_item = $('<p class="orderitem">' + pos.Id + '</p>');
$('#placeholder').append($order_item);
$.each(pos.OrderItems, function (index) {
$order_item.append('<p>' + this.Id +
' ' + this.Description + '</p>');
});
http://jsfiddle.net/xgTt2/4/
Here's the answer:
http://jsfiddle.net/7EmsX/
var serverResponse = [{
"Id": "aaa",
"OrderItems": [{
"Id": 1,
"Description": "Salad"
}, {
"Id": 2,
"Description": "Pizza"
}]
},
{
"Id": "bbb",
"OrderItems": [{
"Id": 3,
"Description": "Salad"
}, {
"Id": 4,
"Description": "Pizza"
}]
}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
var $orderItem = $('<p class="orderitem">' + pos.Id + '</p>');
$orderItem.appendTo('#placeholder');
$.each(pos.OrderItems, function (index) {
$orderItem.append('<p>' + this.Id + ' ' + this.Description + '</p>')
});
});
When you select the .orderitem class, it is selected every pos item and inserting the sub items into it. You want to insert your sub-items only to the current pos item instead.
In second loop run, $('.orderitem') select all of your <p class="orderitem"></p>
Try below:
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
var orderitemHTML = '';
orderitemHTML += '<p class="orderitem">' + pos.Id + '</p>';
$.each(pos.OrderItems, function (index) {
orderitemHTML += '<p>' + this.Id + ' ' + this.Description + '</p>';
});
$('#placeholder').append(orderitemHTML);
});

Categories