How do I iterate over object literal array with jquery $.each() method? - javascript

how do I iterate over object literal array with jquery $.each() method?
In the chrome debugger, it comes back as "undefined, undefined".
Any help would be really appreciated. thanks!
var links = [
{ className : 'hover', url : 'http://www.yahoo.com' },
{ className : 'hover-2', url : 'http://www.foxnews.com' },
];
loopy(links)
function loopy(obj){
$.each(
obj,
function(){
console.log(obj.className + ', ' + obj.url);
}
);
}

Try:
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
The $.each function parameter takes two arguments -- the index of the current item in the array, and the second is the actual current value of the array.
See the API for some more explanation and examples.
You can see this fiddle to see it in action.

I just wanted to offer a slightly modified version of David's response that will be a little more gentle on the DOM when processing larger objects.
Original answer (above):
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
This solution works, but it generates an entirely new instance of the iterator function for every property in the object. There's no need for that, and I think you'll find more stable performance in larger applications by declaring specific methods to handle that sort of thing.
Try this:
// Process a property in your link object
function links_iterationHandler(i, val) {
console.log(val.className + ', ' + val.url);
}
// Traverse the link object and pass each result off to the method above
$.each(obj, links_iterationHandler);
This essentially does the same thing, but doesn't hammer on the DOM as much. It's not a big deal if you only have a few items in your object. But if you're dealing with a lot of data, like a big recordset loaded via Ajax, it will make a difference for sure.
Cheers!

I would try this:
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
The first property is the index.
http://api.jquery.com/jQuery.each/

Related

How to use jQuery forEach statement?

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

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

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

'length' is null or not an object? IE 8

I get the following error in IE8:
length is null or not an object
Anyone have any ideas? Feedback greatly appreciated.
function refresh() {
$.getJSON(files+"handler.php?action=view&load=update&time="+lastTimeInterval+"&username="+username+"&topic_id="+topic_id+"&t=" + (new Date()), function(json) {
if(json.length) {
for(i=0; i < json.length; i++) {
$('#list').prepend(prepare(json[i]));
$('#list-' + count).fadeIn(1500);
}
var j = i-1;
lastTimeInterval = json[j].timestamp;
}
});
}
Just check for the object being null or empty:
if (json && json.length) {
// ...
}
C'mon gang this was glaringly obvious :-)
JSON objects (returned by jQuery or otherwise) do not have a length property. You'll need to iterate over the properties, most likely, or know the structure and simply pull out what you want:
$.getJSON( ..., ..., function( json ) {
for( var prop in json ) {
if( !json.hasOwnProperty( prop ) ) { return; }
alert( prop + " : " + json[prop] );
}
} );
Alternatively, grab a library like json2 and you'll be able to stringify the object for output/debugging.
pop the JSON in a span then clip it and paste it here so we can see it:
<span id="JSObject2">empty</span>
with the json2.js from here: (link for it at bottom of the page) http://www.json.org/js.html
myJSON = JSON.stringify(json);
$('#JSObject2').text(myJSON);
Using that, we can help you better, and you can see what you have!
What does your returned JSON look like? If you're returning an object, length might not be explicitly defined, whereas if you're returning an array, it should be defined automatically.
First thing that comes to mind is that length is not a property of whatever json is. What is the json variable supposed to be anyway?
A JSON is an object, you seem to be treating it like an array. Does it really have a length property? Show us the JSON?
You might need to use a for..in instead.
EDIT: Can you make the JSON from the backend structure like so?
({
"foo": []
})

Categories

Resources