ignore case in for loop when property does not exist - javascript

I am making a GET request to an endpoint.
This returns an array containing many objects, some of which contain a url for a photo.
If the individual object contains a photo I want to display it, if not just ignore.
I expected the following code to work, and ignore the cases where the photo does not exist, but I am still getting the following error message.
Uncaught TypeError: Cannot read property '0' of undefined(…)
$.get(url, function (data) {
for(var i = 0; i < data.length; i++){
if(data[i].media[0].img){
console.log(data[i].media[0].img);
}
}
});

$.get(url, function (data) {
for(var i = 0; i < data; i++){
if(data[i].media && data[i].media[0]){
console.log(data[i].media[0].img);
}
}
});

Related

Get Pointer Id only , using Parse

this returns an object. I just want to get the id. I will use it for a query
var q= new Parse.Query("Comments");
q.find({
success: function (results) {
for (var i=0; i< results.length;i++) {
console.log(results[i].get("user_id"));
}
});
i actually found it out by exploring, i've used to access just the id
results[i].get("user_id").id

Why am I getting a typeError of property 'length' undefined?

I'm getting "Cannot read property 'length' of undefined" for:
success: function(data) {
for(i = 0; i < data.length; i++) {
var callData = data.query.search[i].title;
$("#results").html(JSON.stringify(callData));
}
Since I'm passing data into the function, shouldn't data.length be recognized in the for loop? For context I'm making an AJAX call.
In most cases it means that data might be null or undefined.
But here you have different case: Your data is an object, not a collection, so it does not have length property.
You are iterating over data.query.search collection, but you are checking data length
success: function(data) {
if(!data.query.search) { return; } // check if collection is present
for(i = 0; i < data.query.search.length; i++) {
var callData = data.query.search[i].title;
$("#results").html(JSON.stringify(callData));
}
}

Parsing JSON array of objects: undefined property

So, similar to my my previous question here (I was unsure whether to make a new question or edit the old one), I managed to sucessfully parse the body JSON response using the code seen below.
However when attempting to do the same to the event_calendar_date, I get this: Failed with: TypeError: Cannot read property 'und' of undefined. I would have assumed that to get to the next object in the array the method would be the same for both, however that does not appear to be the case.
JSON response from the server:
[
{
"revision_uid":"1",
"body":{
"und":[
{
"value":"Blah Blah.",
"summary":"",
"format":null,
"safe_value":"Blah Blah.",
"safe_summary":""
}
]
},
"event_calendar_date":{
"und":[
{
"value":"2015-07-20 14:00:00",
"value2":"2015-07-20 20:00:00",
"timezone":"America/New_York",
"timezone_db":"America/New_York",
"date_type":"datetime"
}
]
}
}
]
My Code:
Parse.Cloud.httpRequest({
method: "GET",
url: 'http://www.scolago.com/001/articles/views/articles',
success: function(httpResponse) {
var data = JSON.parse(httpResponse.text);
var articles = new Array();
for (var i = 0; i < data.length; i++) {
var Articles = Parse.Object.extend("Articles"),
article = new Articles(),
content = data[i];
article.set("body", content.body.und[0].value);
article.set("vid", content.vid);
article.set("title", content.title);
article.set("events", content.event_calendar_date.und[0].value);
articles.push(article);
};
// function save(articles);
Parse.Object.saveAll(articles, {
success: function(objs) {
promise.resolve();
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
I am afraid you didn't give us all code, or you are using not the code you posted in this question, because it should run fine, as you can see in this demo:
for (var i = 0; i < data.length; i++) {
var content = data[i];
console.log(content.event_calendar_date.und[0].value);
};
EDIT and solution
As I expected, JSON you are getting doesn't have field event_calendar_date for 2nd, and 3rd object. I checked in your full code on GitHub.
First object has correct event_calendar_date field, but next records don't have. See how is JSON you are getting formatted - http://www.jsoneditoronline.org/?id=b46878adcffe92f53f689978873a3474.
You need to check first if content.event_calendar_date is present in record in your current loop iteration or add event_calendar_date to ALL records in JSON response.

Displaying JSON data in Javascript loop

I am having an issue displaying json data. I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" comes back as undefined.
Why is object undefined? From everything I can see I am doing it right.
My json that is returned.
{
"data":[
{
"NumberOfAnswers":25,
"Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":54.35
},
{
"NumberOfAnswers":21,
"Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":45.65
}
]
}
And here is the function to display it. (With some debugging code as well)
function format(notes) {
console.log(notes); //this displays the json
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
Here is the ajax function:
$.ajax({
type: 'post',
url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
success: function(result) {
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
detailsrows.splice(RowID, 1);
} else {
row.child(format(result)).show();
tr.addClass('shown');
if (RowID === -1) {
detailsrows.push(tr.attr('id'));
}
}
}
});
Most likely, the response is still in string format. You can add JSON.parse to convert it to an object and then be able too access the data property.
Try modifying your function like this to see if it fixes the problem.
function format(notes) {
console.log(notes); //this displays the json
// The following converts the response to a javascript object
// and catches the exception if the response is not valid JSON
try {
notes = JSON.parse(notes);
} catch(e) {
console.log('notes is not valid JSON: ' + e);
}
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}

json request with data variables - how do I read the variable in the function?

Loading in a bunch of json files from an array called bunchOfData. The .url is the url for each json file.
How do I read my variable "myI" in the processData function?
for(var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){}).success(processData);
function processData(ds){
console.log(ds.myI); //undefined
}
}
function successHandler(i){
console.log('i is instantiated/stored in the closure scope:',i);
return function(data, textStatus, jqXHR){
// here, the server response and a reference to 'i'
console.log('i from the closure scope:',i, 'other values',data,textStatus,jqXHR);
}
}
var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){}).success(successHandler(i));
}
You cannot access varibles outside of scope, the response will only be valid
function(ds){
// Here
}
Try this:
for(var i = 0; i < bunchOfData.length; i++){
$.getJSON(bunchOfData[i].url, {"myI":i}, function(ds){
console.log(ds);
});
}
Also once the request is finished and was successfull contents of success will run, note that what you are trying to achive can be dont with a single request (you can unify the files and serv them in a single one), so you get the data and then iterate.

Categories