How to iterate objects in json whit jQuery - javascript

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

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

Accessing a value in JSON

I am trying to access the country names from this json -
https://restcountries.eu/rest/v1/all
This is my code for loading that json -
<script>
(function() {
var country = "https://restcountries.eu/rest/v1/all";
$.getJSON( country)
.done(function( data ) {
$.each(data, function(key, value) {
$('#mySelect').empty();
$('#myselect').append('<option>' + data.name + '</option>');
});
});
})();
</script>
The problem may be in data.name statement. I couldn't find any solution on my own. Plus, i am new to JSON. Any help or at least any comment to point my faults will be appreciated.
it should be value.name, data is the array you get from the api, value is each item in the array. also, remove empty as it's remove everything in each loop cyle...
see working code here

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

Parse JSON response from Servlet

Ok, Ive got a Java Servlet returning some JSON (In Application/JSON format). To do this, im using the GSON libary.
The Servlets GET method takes one paramater, ID. The servlet seems to be working, For example,chrome shows my AJAX GET request returning the following when the [Booking]ID paramater sent is 1.
0: {WidgetID:46, BookingID:1, X:393, Y:50, Content:Test1}
1: {WidgetID:47, BookingID:1, X:337, Y:251, Content:Test2}
2: {WidgetID:48, BookingID:1, X:97, Y:198, Content:Test3}
The problem I have is with parsing this response. Here is my JS code:
loadPositions() {
var BookingID =
if (BookingID != null && BookingID != "null")
{
var data = {"id" : BookingID};
$.getJSON("Widget", data, function(data) {
// Successfully got all this bookings widgets as JSON, TODO: Parse this!
});
}
}
What should I put in the "TODO: Parse this!" section?
I want to foreach over all the elements, and grab their data. I really suck at this JQuery stuff.
In the todo section, you should do the following to loop through all the arrays:
$.each(data, function(index,value){
// here index=0 & value.WidgetID=46, value.BookingId = 1, use it as you would like to.
})
Have a look at jQuery .each()
http://api.jquery.com/jQuery.each/
and for a good example of what you want to do...
http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.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');
});
Take a look at
https://github.com/acobley/jBoggyAppy/blob/HectorV2-Cassandra-0.7.0/WebContent/Scripts/index.js
the ShowScrollingTags function.

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

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/

Categories

Resources