How to loop through object in Jquery? - javascript

I am getting TypeError: field[i] is undefined from this:
function ObserverFetch() {
$.ajax({
type: "POST",
url: "Observer.aspx/ObserverFetch",
data: JSON.stringify({ id: "" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
$.each(data, function (i, field) {
alert(field[i].BidderName);
//$('#dvBids').text(field);
//$("#gvDetails").append("<tr><td>" + field.SrNo + "</td><td>" + field.BidderName + "</td><td>" + field.BidAmt + "</td></tr>");
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
This is what I get in field
[{"SrNo":4,"BidderName":"faisal","BidAmt":6000000.0000,"BidDate":"\/Date(1430199508063)\/"},{"SrNo":3,"BidderName":"arbaaz jalil","BidAmt":5000010.0000,"BidDate":"\/Date(1430199494083)\/"},{"SrNo":2,"BidderName":"arbaaz","BidAmt":500000.0000,"BidDate":"\/Date(1430199483530)\/"},{"SrNo":1,"BidderName":"shekhar1","BidAmt":5000.0000,"BidDate":"\/Date(1430199394957)\/"}]
$('#dvBids').text(JSON.stringify(data)); gives me :
{"d":"[{\"SrNo\":4,\"BidderName\":\"faisal\",\"BidAmt\":6000000.0000,\"BidDate\":\"\\/Date(1430199508063)\\/\"},{\"SrNo\":3,\"BidderName\":\"arbaaz jalil\",\"BidAmt\":5000010.0000,\"BidDate\":\"\\/Date(1430199494083)\\/\"},{\"SrNo\":2,\"BidderName\":\"arbaaz\",\"BidAmt\":500000.0000,\"BidDate\":\"\\/Date(1430199483530)\\/\"},{\"SrNo\":1,\"BidderName\":\"shekhar1\",\"BidAmt\":5000.0000,\"BidDate\":\"\\/Date(1430199394957)\\/\"}]"}
$.each(data.d , function (i, field) { gives me :
TypeError: invalid 'in' operand a

Bizarrely, the response from your server is a JSON object with a single property, d, which is a string containing the JSON for an array. If it's your server method generating that response, you probably want to adjust it so that data.d is an array, not a string.
To get those results and loop through them, you'll need to parse it, and then use field directly rather than via i:
var fields = JSON.parse(data.d);
$.each(fields, function(i, field) {
alert(field.BidderName);
});
or of course:
$.each(JSON.parse(data.d), function(i, field) {
alert(field.BidderName);
});
Side note: As the parsed version of data.d is an array, on any modern browser you can use Array#forEach rather than $.each, which has a slightly less-confusing argument list for the callback. (Array#forEach can be easily polyfilled on IE8 and earlier.)
JSON.parse(data.d).forEach(function(field) {
alert(field.BidderName);
});
Live Example of both:
var data = {
"d": "[{\"SrNo\":4,\"BidderName\":\"faisal\",\"BidAmt\":6000000.0000,\"BidDate\":\"\\/Date(1430199508063)\\/\"},{\"SrNo\":3,\"BidderName\":\"arbaaz jalil\",\"BidAmt\":5000010.0000,\"BidDate\":\"\\/Date(1430199494083)\\/\"},{\"SrNo\":2,\"BidderName\":\"arbaaz\",\"BidAmt\":500000.0000,\"BidDate\":\"\\/Date(1430199483530)\\/\"},{\"SrNo\":1,\"BidderName\":\"shekhar1\",\"BidAmt\":5000.0000,\"BidDate\":\"\\/Date(1430199394957)\\/\"}]"
};
snippet.log("Using $.each:");
$.each(JSON.parse(data.d), function(i, field) {
snippet.log(field.BidderName);
});
snippet.log("----");
snippet.log("Using forEach");
JSON.parse(data.d).forEach(function(field) {
snippet.log(field.BidderName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

The problem is that in var fiel you already have a each element of the array. The solutiobn is:
$.each( obj, function (i, field) {
alert(field.BidderName );
});

Related

"Error : Cannot use 'in' operator to search for 'length' in [{"ID":"2","Name":"EAA2"}]" when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]
I split it into two functions as I didn't want to keep going back to the api everytime a user selects/de-selects an option.
I have also tried the following:
Changing vars to lets
Passing data.d from the update to the populate
function populateAvailableAuthorities() {
var list = $('#availableAA');
var data = JSON.parse($('#AAJSON').val());
var auths = $('#tbSelectedAA').val();
list.empty();
$.each(data, function (key, entry) {
if (!~auths.indexOf(entry.ID + ';')) {
list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
}
});
}
function updateListboxes() {
var teams = '';
let aa = $('#AAJSON');
aa.empty();
$('#cblTeams input:checked').each(function () {
teams += $(this).attr('value') + ',';
});
if (teams.length > 1) {
teams = teams.substr(0, teams.length - 1);
$.ajax({
type: "POST",
url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
data: '{teams: "' + teams + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
aa.val(JSON.stringify(data.d));
populateAvailableAuthorities();
}
});
}
}
It would seem that "over-stringifying" is an issue with JSON. If I doubled the JSON.parse or removed the JSON.stringify it all works correctly.
Annoying!!

JSON values are showing NaN

While retrieving JSON array data using $.each method, I am able to get the array values, but apart from that it's showing 'NaN' values and showing the below error.
"Uncaught TypeError: Cannot use 'in' operator to search for '5' in Hello!"
Seems it's looping through all the objects not only array, if this is the case how can I get only array values and how can I get all the values(including and excluding array values).
one more query does this rawgit works for only method 'GET', because while using method 'POST' throwing error(403 (Forbidden)).
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
$.each(data, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
JSON:
{
"items": [
{
"key": "First",
"value": 100
},{
"key": "Second",
"value": 200
},{
"key": "Last",
"value": "Mixed"
}
],
"obj": {
"number": 1.2345e-6,
"enabled": true
},
"message": "Hello!"
}
It sounds like you only want to iterate data.items but you're iterating over everything. Try this:
$.each(data.items, function(index, obj) {
$('#show-data').append(obj.key + obj.value + '<br/>');
});
https://jsfiddle.net/rrsku4Lq/
The problem is when the second loop reaches "message": "Hello!", that is not a object to be looped again, so for that element only the first loop is needed.
To correct, just make an if statement to enter the second loop only in case obj is an Object.
I also changed the nested loop index name to index2.
$.each(data, function(index, obj){
// Only do nested loop if obj is Object
if (obj instanceof Object) {
$.each(obj, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});
If you're only interested in data.items, than you can use
$.each(data.items, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
You have an unnecessary for loop. The response is one JSON object in your case. You simply need to iterate the data items. UPDATE: How you handle a response depends on what you want to accomplish. In practice, you'll generally know how to access the data you need from the response, but as others have suggested, you can iterate through the keys in the response object and check for types
var object = {
arr : [1,2,3],
nestedObject : { }
};
for (var key in object) {
console.log(key);
console.log('Is array? ' + Array.isArray(object[key]));
// Now you can handle the data based on it's type...
}
In this case, you could choose to expect the response to include a items key and iterate over that. (It's also good practice to validate that you can process the response)
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function(data) {
// data is your JSON object.
data.items.forEach(function(item) {
$('#show-data').append(item.key + item.value + '<br/>');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-data"></div>
Also, 403 indicates that the resource is blocked for the current user. Verify that your POST method is publicly accessible and that you are authorized to make the request.
You should parse the json first. And as #Jason P said, iterate data.items
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
var parsedData = $.parseJSON(data);
$.each(parsedData.items, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
You are looping through all the elements in the array. I think you need to loop through only 'items' element as only that element contains the 'key' and 'value' elements.
Even though you are doing that, you can check if the key and value element exists, and if it does, do whatever your code wants.
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data)
{
$.each(data, function(index, obj)
{
$.each(obj, function(index, element)
{
if(element.hasProperty('key') && element.hasProperty('value'))
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
console.log(data.items);
$.each(data.items, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});

Return Only Specific Values From Ajax JSON call

I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

json get field name

I want to push the Field Names into the option value and the result into the text of a select. It should look like this:
<select id="ddl_fields">
<option value="RoleId">e407d28a</option>
<option value="RoleName">Sales</option>
</select>
This is the json object returned from the database:
"[{"RoleId":"e407d28a","RoleName":"Sales"}]"
This is the code and it pulls back a valid result:
function getFields(){
var the_id = $(".hid_ID").val();
var jsonText = JSON.stringify({ id: the_id });
$.ajax({
type: "POST",
url: "bc_Admin.aspx/getFields",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "0") {
var obj = $.parseJSON(data.d);
//what needs to change???
$.each(obj, function (index, value) {
$('#ddl_fields')
.append($("<option value=" + value.id_Role + ">" + value.RoleName + "</option>"));
});
}
} //end success
});
}
Similar to this questions but need a JQuery solution.
How to get/list all field names of a JSON data with ExtJS?
Thanks!
Assuming that data.d is in the format you posted obj is an array and you want to iterate the object in the array and not the array itself.
$.each(obj[0], function (index, value) {
$('#ddl_fields')
.append($("<option value=" + index + ">" + value + "</option>"));
});
You have to iterate through the keys of the object, and use hasOwnProperty to make sure its a key of the object and not of its prototype.
var key, keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key))
keys.push(key)
}
You'll want to loop through the object and use hasOwnProperty().
for (var i in inputData) {
if (inputData.hasOwnProperty(i)) {
console.log(i + " , " + inputData[i]);
}}
This example will just log to console key: value.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Just change
$.each(obj, function (index, value) {
to
$.each(obj[0], function (index, value) {
The problem is that you return an array in your json
Not sure if I understand, but here's what I would do to get what you want (I made also your code simplier):
function getFields(the_id){
$.ajax({
type: "POST",
url: "bc_Admin.aspx/getFields",
data: { id : the_id },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for(var i = 0; i < data.length; i++){
console.log(i + ": " + data[i]);
}
},
error : function(s , i , error){
console.log(error);
}
});
}

Categories

Resources