I'm trying to handle an object which doesn't exist in the array.
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
So, when the javascript code gets here, it fall over because there happens to be nothing in the actual string it is trying to parse. I've tried catching it with "typeof", but that doesn't work either. I'm stumped.
So, the data.flightStatuses[i] array exists, just not the .airportResources.departureGate.
I tried to see if it exists using "typeof data.flightStatuses[i].airportResources.departureGate". It still falls over.
alert (typeof data.flightStatuses[i]) // this comes back "object"
alert (typeof data.flightStatuses[i].airportResources.departureGate) // it dies...
Should be fairly straight forward like this:
if (data.flightStatuses[i].airportResources.departureGate) {
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
}
It looks like your problem is with airportResources, and not with departureGate.
Try this:
var departureGate = null,
ar = data.flightStatuses[i].airportResources;
if(ar && 'departureGate' in ar){
departureGate = JSON.stringify(ar.departureGate);
}
Cheers
You can check if the departuregate is defined as a property at all like this, and then do the action you wanted, for example:
if(data.flightStatuses[i].airportResources.hasOwnProperty('departureGate') {
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
} else {
var departuregate = null; // for example
}
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Related
I'm trying run a script if URL doesn't contain specific string. Here is what i have so far:
var ignorePages = ['page1','page2','page3'];
if (window.location.href.indexOf($.inArray(ignorePages)) === -1) {
// do something
}
But this is not working. I would like to test if the string is found in array and if not, execute. Searched the SO Q/A but couldnt find a solution via array using jQuery's inArray.
You can do this easily with underscore. I also think you may want to use location.pathname instead of location.href. Anyhow, this is how I would do it.
import { contains } from 'underscore';
let blacklist = ['/splash', '/login', '/feed' ];
if (! contains(blacklist, window.location.pathname) {
/* do stuff here */
}
Thanks all for pointing in right directions. I've solved it with correct usage of inArray:
var ignorePages = ['/page1','/page2','/page3'];
var currentUrl = window.location.pathname;
if ($.inArray(currentUrl, ignorePages) === -1) {
// do something
}
I have this JavaScript row:
var matcherName = new RegExp(filterValueName);
The filterValueName variable has some string but, might be situation when filterValueName is undifined .
My question is how can I know if matcherName was constructed by filterValueName = undifined?
Why not testing filterValueName first?
Something like
var matcherName = null;
if( filterValueName != undefined ) {
var matcherName = new RegExp(filterValueName);
}
...
if( matcherName === null ) {
// filterValueName was undefined
} else {
// filterValueName was ok
}
In Firefox and Chrome at least the regex defaults to /(?:)/. But just compare the strings to be sure:
function is_regex_undefined(regex) {
var undefined;
return String(regex) === String(new RegExp(undefined));
}
According to MDN the pattern should not be absent. I would not doubt that there might be a JS engine where new RegExp(undefined) equals /undefined/. Then this solution would fail if you really have an expression that should match the string "undefined". #RiccardoC's answer is the safer choice.
I would recommend having an if statement before, since you can't easily extract what you constructed it with. Is there anything preventing you from testing the values before you work with them?
var matcherName = new RegExp("foo");
var matcherName2 = new RegExp(undefined);
console.log(matcherName)
VM522:2 /foo/
console.log(matcherName2)
VM527:2 /(?:)/
var status = result.locations[index].status;
var operator = result.locations[index].operator;
var original = result.locations[index].original;
var produced = result.locations[index].produced;
var href = result.locations[index].more;
I have the above which each need to be an if statement to check if there is content and my output is the below code.
if (result.locations[index] && result.locations[index].status){
var status = result.locations[index].status;
} else {
var status = '';
}
I would need to reproduce this per line from the code at the top of the post. What would be the best method to simplify each down to keep the code neater and not produce 5 lines of if statement when 1 or 2 would do.
var status = (result.locations[index] && result.locations[index].status ? result.locations[index].status : '');
Not sure why you want to, but:
var status = (result.locations[index] && result.locations[index].status) ? result.locations[index].status : ""
Your problem is trying to access a property of a "deep" javascript object using its path.
This is a common question :
Javascript: Get deep value from object by passing path to it as string
Accessing nested JavaScript objects with string key
There is no built-in way to do this in javascript.
There are plenty of libraries to do that, for example, with selectn, this would become something like (I have not tested it, so I don't know if the index part will work, but you get the idea) :
var status = selectn("locations." + index + ".status", result) || ''
If the structure of your objects is always the one above (that is, the property is just at one level of depth), and you're not expecting 'falsy', you could simply write the 'test' function yourself :
function safeGet(instance, propertyName, defaultValue) {
// As pointed by AlexK, this will not work
// if instance[propertyName] can be anything Falsy ("", 0, etc...)
// If it's possible, get a library that will do
// the full series of insane checks for you ;)
if (instance && instance[propertyName)) {
return instance[propertyName];
} else {
return defaultValue;
}
}
var location = result.locations[index]; // Potentially undefined, but safeGet will deal with it
var status = safeGet(location, "status", "");
var operator = safeGet(location, "operator", "DEFAULT_OPERATOR");
...
var status = result.locations[index] && result.locations[index].status || '';
However, better maje sure before, if result.locations[index] exists... else do whatever is to be done in your code..
I have an array which I'm adding objects to dynamically like so
var _plugins = [];
this.registerPlugin = function(plugin){
_plugins.push(plugin);
plugin.onInit()
},
This is all within a class and I am trying to use a method like this which should run the method passed in to meth
this.runPluginMethod = function(meth, call_obj){
for (x in _plugins){
x[meth](call_obj)
}
}
The Objects I am adding to the _plugins array are created like this
var ourPlugin = Object.create(babblevoicePlugin);
Object.defineProperty(ourPlugin, 'onInit', {value : function()
{
console.log('this is from reflex oninit')
}});
When I try running mianClass.runPluginMethod('onInit', 'a') It does nothing, doesn't run console.log like it should to my mind.
Can anyone help? am I doing something wrong? is this possible?
I think the problem is here:
this.runPluginMethod = function(meth, call_obj){
for (x in _plugins){
x[meth](call_obj)
}
}
You're trying to access a property of a key instead of the object you're looking for. Changing it to the following should work.
this.runPluginMethod = function(meth, call_obj){
for (x in _plugins){
_plugins[x][meth](call_obj)
}
}
EDIT
As another example, check the output of the following in a js console:
x = ['a','b','c'];
for (i in x){ console.log(i, x[i]) };
This is probably easy for someone.
I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable
var campaignList = res.DATA.CAMPAIGNS
Now, given a specified campaignID passed in the URL
var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'
I want to check if the returned list contains this campaignID
Any help much appreciated.
Plenty of ways to do it, but I like nice data structures, so ...
Split the list on comma, then loop over list, looking for value:
function campaignExists(campaignList,campaignId) {
aCampaignList = campaignList.split(',');
for (i=0;i<aCampaignList.length;i++) {
if (aCampaignList[i]==campaignId)
return true;
}
return false;
}
Since Array.indexOf sadly isn't cross browser, you're looking at something like:
// assume there is no match
var match_found = false;
// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
if (parseInt(campaignList[i]) === parseInt(campaignId)) {
match_found = true;
break;
}
}
If you need to do this repeatedly, wrap it in a function
Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:
var campaignIDs = {12 : 12, 45 : 45, 66 : 66};
campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false
This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:
http://jsfiddle.net/bittersweetryan/NeLfk/
I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.
var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;