How to use jQuery forEach statement? - javascript

Note please. (I'm currently using the Spring Framework (MVC))
The value sent from Controller to ajax is ...
It looks like the picture above.
I am looping through the forEach statement for the values in that array, and I want to put the value into the tag.
So I wrote the code.
$(function()
{
$('#doctorSelect').change(function()
{
$('#selectGugan').show();
var doctor_idx = $(this).val();
$.ajax
({
type: 'POST',
url: 'selectDoctor.do',
data: {"d_idx":doctor_idx},
dataType: 'JSON',
success: function(sectionDate)
{
console.log(sectionDate);
var html = "<option value=''>Choice Doctor</option>";
var responseData = [];
responseData.push(sectionDate);
console.log(responseData);
$.each(responseData, function(key, value)
{
console.log("forEach statement in responseData :" + responseData);
//html+="<option value="+new_date+">"+new_date+"</option>";
});
$('#doctorSelect_2').html(html);
},
error: function(sectionDate)
{
console.log("data : " + sectionDate);
}
});
});
});
But unexpectedly, I do not get the key, value.
In fact, I don t know about the jquery forEach statement.
How do I set key, value?
I just want to bring those values and express it like this.
<option value="ri_idx">ri_startDate ~ ri_endDate</option>
How to set key, value or How to use jquery forEach statement ?
I am a beginner. I would appreciate it if you could give me an example.

In your case I am not sure why would you be doing this:
responseData.push(sectionData);
because this way you dont get an array of objects as I believe you thought you would, you simply will get an array with 1 element in it, which is many objects, so doing a forEach on that array will not help, because the value will be the multiobject element (not a single object that you could access properties).
What you want to do is iterate over your original objects, so your code should be something like this:
$.each(sectionDate, function(key, value){
// here you can access all the properties just by typing either value.propertyName or value["propertyName"]
// example: value.ri_idx; value.ri_startDate; value.ri_endDate;
});
Hope this helps!

In jQuery forEach working like this
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If you are using Array for loop than key is array index and value values and if you are using javascript object then object key is key and value is object value for the particular key.
You can read more at jQuery documentation.

Just use property names in object. Check if this helps
$(document).ready(function() {
var responseData = [
{startdate: '2017-12-21', enddate: '2017-12-22', idx: '1'},
{startdate: '2017-11-21', enddate: '2017-11-22', idx: '1'},
{startdate: '2017-10-21', enddate: '2017-10-22', idx: '1'}
];
var html = '';
$.each(responseData, function(key, value) {
html += "<option value=" + value.startdate + ">" + value.startdate + "</option>";
});
$('#doctorSelect').html(html);
});

Related

$.each function is not iterating

I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});

how to iterate each array element in response in $.ajax

First thing, the simple response which I get back from $.ajax is this:
http://pastebin.com/eEE72ySk
I am using this code:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
I was trying this code:
$.each(result.Response.Results[0][0].AirlineRemark, function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
When I use the above code, then error is:
Uncaught TypeError: Cannot use 'in' operator to search for '5' in IndiGo
When I tried this code without the forEach loop :
$("#divResult1").text(result.Response.Results[0][0].AirlineRemark);
I get no error but the output is only the first one. Indigo is showing however in response there are 20 arrays in Results. I have shown only two arrays in result in the link provided above.
Please someone tell me how to iterate each and every item in results array.
AirlineRemark is not an Array, so looping through that one is not possible. So loop through the array of arrays, and find the property within each loop
$.each(result.Response.Results[0], function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
You're trying to iterate a non-array there. If, result is based on your JSON that you provided. This is one way you can iterate it,
// Each items in result.Response.Results
$.each(result.Response.Results, function(i, items) {
// Get the AirlineRemark at the item at 0 index.
var airlineRemark = items[0].AirlineRemark;
// Append it to #divResult1
$("#divResult1").append('<p>' + airlineRemark + '</p>');
});
Beware that on sample above, items is an array. And it will only get the first item.
You can try this
$.each(result.Response.Results, function () {
$("#divResult1").append('<p>'+this[0].AirlineRemark+'</p>');
});

Splitting a string into words has resulted in splitting into letters

I'm new to Javascript. I need to split a string of this format:
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
and create as options for select tag. I tried the below code
$.each(data, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
But I get strings split as letters.
What can I do to split the string to get options as
<option>Man1</option>
<option>SKC2</option>
Note : Some times this string may contain spaces as well.
If data is your string, then parse it from JSON to a JavaScript array of strings, then iterate over that:
var yourArray = JSON.parse(data);
$.each(yourArray, function(index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
Try to pass the array first and then pass the translated array as the html string,
$('#bu_group').html($.map(JSON.parse(data),function(val,i){
return "<option value="+ val +">" + val + "</option>";
}));
DEMO
As data is actually coming from your server via ajax you can simply specify correct dataType.
Either
$.ajax({dataType: 'json', ...}).done(function(data){
//data will be parsed
});
Or
$.getJSON(url).done(function(data){
//data will be parsed
});
Or configure your server to return correct mime type (application/json)
if your data is
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then there is no problem, so I think you have your data as :
'["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]'
which you must 'parse' it.
as you are using jQuery, one option is to parseJSON like this:
var parsed_array = $.parseJSON('["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]');
after doing that, you can successfully do :
$.each(parsed_array, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
If you have your data as
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then you can iterate this var, isn't it?
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"];
for(i=0;i<data.length;i++) {
$('#bu_group').append($('<option/>', {
value: data[i],
text : data[i]
}));
};
JSFiddle here

How to iterate objects in json whit jQuery

I am returning one JSON response from the server:
{'error':'true',fields:[[{'pk':2,'title':'test'}],{'votes':20,'cant':{1:0,2:3}}]}
Console Dev return
Object { error="true", fields=[2]}
I'm trying to get all the data fields[2], but not work, I'm doing something:
$.each(data.fields, function(i,item){
console.log(data.fields[i]);
})
Question: I know that I'm doing wrong, I want to access all the data in the order fields[2], pk and title.
Thanks.
You can fetch fields[2] using following:
$(data.fields).last()[0] // Give {votes: 20, cant: Object}
which you can use to iterate and get all data as:
var other_data = $(data.fields).last()[0]
$.each(other_data, function(key, value){
console.log('key : ' + key + ' value: ' + value);
});
Your code is need some corrections try this,
Demo
$.each(data.fields[1], function(i,item){
console.log(item);
})

how to browse a javascript object

I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});

Categories

Resources