I'm working with an API call that's returning JSON and in some scenarios some of the data is empty. For example, the snippet below shows that roleBusinessScopes is empty.
{
"userProfile": {
"organizationContacts": [
{
"roleBusinessScopes": {}
}
]
}
}
I wanted to be able to check if roleBusinessScopes is empty. I tried roleBusinessScopes.length = 0, however, that doesn't work.
When roleBusinessScopes does return data...
"roleBusinessScopes": {
"businessScopes": {
"scopeName": "something"
}
}
... I can check for that:
if (organizationContacts[i].roleBusinessScopes.businessScopes[0].scopeName !== "something")
{
// do something
}
How can I check if roleBusinessScopes has no data?
You can use Object.keys(obj).length > 0 to check if object has some keys (data) or not
if (Object.keys(organizationContacts[i].roleBusinessScopes).length > 0) {
// Not empty
} else {
// empty
}
Assuming the structure is always the same (and that you're in a ideal world where you don't need to check the validity of each property and child object), you could just check if businessScopes is not undefined.
let objectWithoutRoleBusinessScopes = {
"userProfile": {
"organizationContacts": [{
"roleBusinessScopes": {}
}]
}
};
let objectWithRoleBusinessScopes = {
"userProfile": {
"organizationContacts": [{
"roleBusinessScopes": {
"businessScopes": {
"scopeName": "something"
}
}
}]
}
};
function hasRoleBusinessScopes(objectToTest) {
return objectToTest.userProfile.organizationContacts[0].roleBusinessScopes.businessScopes != undefined;
}
console.log(hasRoleBusinessScopes(objectWithoutRoleBusinessScopes));
console.log(hasRoleBusinessScopes(objectWithRoleBusinessScopes));
You could try using Object.keys({your_object_here...}) and check the length of the returned array.
You should be able to do something like
if (Object.entries(organizationContacts[i].roleBusinessScopes).length === 0) {
// do something
}
Object.entries() will return a list of all the object's properties, which you can use to key in on length.
You could simply check if it is empty or not by this statement
if(organizationContacts[i].roleBusinessScopes === {}){
// handle empty case here
} else {
// handle non-empty case here
}
What I would use is a function to check it as there are multiple possibilities .
Sometimes a server will write null in its place so alternative checks need to be made
Us this function
function checkempty(jsonString) {
if (jsonString == null ||
jsonString == undefined ||
jsonString.length == 0) {
console.log("Name cannot be empty\n");
return false;
} else {
console.log("Your response has been recorded\n");
return true;
}
}
checkempty(Object.keys(organizationContacts[i].roleBusinessScopes))
Related
The 1st set of code works fine and assigns non-empty objects to the var, but the 2nd code with only log the right data but will not return the data. The var just remains undefined.
Any idea on where I am going wrong? Thanks!
var filteredEmpty1 = json_data.children.filter(function(value, index, arr) {
if (value.children.length != 0) {
return value//Returns what I need
} else {
console.log("EMPTY")
};
});
json_data = filteredEmpty1;
json_data = {
"name": "RVs",
"children": json_data
};
var filteredEmpty2 = json_data.children.forEach(function(value) {
value.children.filter(function(e) {
if (e.children.length != 0) {
console.log(e)//Logs what I need to return
return(e)//Returns undefined
} else {
console.log("EMPTY")
};
});
})
Use Map instead of forEach because Map returns a value. and Filter function always returns boolean.
var filteredEmpty2 = json_data.children.map(function(value) {
return value.children.filter(function(e) {
return e.children.length != 0;
});
})
I have a method that takes a language abbreviation and matches it using a .constant dictionary, and returns the matching language name.
How can I do an evaluation with .filter to check whether the passed isoCode/language abbreviation exists?
Here is my method:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
var categoryObject = Languages.filter(function ( categoryObject ) {
return categoryObject.code === isoCode;
})[0];
return categoryObject.name;
};
}]);
Here is the method with some error catching I have tried:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
var categoryObject = Languages.filter(function (categoryObject) {
if (isoCode != null || isoCode != undefined) {
return categoryObject.code === isoCode;
}
else {
return categoryObject.code === 'und';
}
})[0];
if (categoryObject.name != undefined || categoryObject.name != null) {
return categoryObject.name;
}
else {
return "undefined";
}
};
}]);
Thank you!
I would recommend you organize your data at Languagesin an object or map, it'll be much faster and simpler when you fetch your translation by an abbreviation. A short example:
angular.module('portalDashboardApp')
.factory('Languages', function(){
var dictionary = {
ISO: {name: 'International Organization for Standardization'}
};
return {
get: function(abbr){
return dict[abbr];
}
};
}).service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
if(!isoCode) {
return "Answer for empty isoCode";
}
var categoryObject = Languages.get(isoCode);
return (categoryObject || {}).name || "I don't know this abbr";
};
}]);
I'm not sure that this JS works without any syntax error (I've not try to launch it) but idea is that you don't need array and filter on big dictionaries and you are able to get any abbreviation from dict with O(1) complexity even with huge dictionary.
If you don't want to have a refactoring with your code you can do something like this:
angular.module('portalDashboardApp')
.service('ISOtoLanguageService', ['Languages', function(Languages) {
this.returnLanguage = function(isoCode) {
if (!isoCode) {
return;
}
var resultAbbrs = Languages.filter(function (categoryObject) {
return categoryObject.code === isoCode;
});
if (resultAbbrs.length > 0) {
return resultAbbrs[0].name;
}
};
}]);
In this case if isoCode is null, undefined or empty string or this key is not found in dictionary return undefined will be by default. Outside you should check a result of this function with if (result === undefined) ...
I hope it helped you)
I have the following JSON:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 0
},
"objects": []
}
I'm interested in objects: I want to know if objects is empty and show an alert:
something like this:
success: function (data) {
$.each(data.objects, function () {
if data.objects == None alert(0)
else :alert(1)
});
i don't know what is you meaning about empty object, but if you consider
{}
as a empty object, i suppose you use the code below
var obj = {};
if (Object.keys(obj).length === 0) {
alert('empty obj')
}
Use Array's length property:
// note: you don't even need '== 0'
if (data.objects.length == 0) {
alert("Empty");
}
else {
alert("Not empty");
}
This is the best way:
if(data.objects && data.objects.length) {
// not empty
}
And it's the best for a reason - it not only checks that objects is not empty, but it also checks:
objects exists on data
objects is an array
objects is a non-empty array
All of these checks are important. If you don't check that objects exists and is an array, your code will break if the API ever changes.
You can use the length property to test if an array has values:
if (data.objects.length) {
$.each(data.objects, function() {
alert(1)
});
}
else {
alert(0);
}
this was what i did, thanks #GilbertSun, on a jsonp callback when I got an undefined with data.objects.length
success: function(data, status){
if (Object.keys(data).length === 0) {
alert('No Monkeys found');
}else{
alert('Monkeys everywhere');
}
}
Js
var myJson = {
a:[],
b:[]
}
if(myJson.length == 0){
//empty
} else {
//No empty
}
Only jQuery:
$(myJson).isEmptyObject(); //Return false
$({}).isEmptyObject() //Return true
I need to check if a property contains a property, right now I am using if statements like in the example
Heres an example object
var Foo = {
"bar" :
{
"foobar":
{
"barfoo":1
}
}
}
And I need to check if barfoo exists, but first I need to check if all the other properties are there, because they might not be depending if another function has been run or not. I can't really lessen the levels of this structure either so that isn't an option.
Currently I am doing something similar to this:
var d = Foo;
if (d) {
d = d.bar;
if (d) {
d = d.foobar;
if (d) {
d = d.barfoo;
if(d){
console.log(d);
}
}
}
}
You could do it all in one if statement:
if (d && d.bar && d.bar.foobar && d.bar.foobar.barfoo)
This works because the javascript stops checking the if statement if any of the elements fail, so it doesn't error with something like cannot check property of undefined.
Otherwise you could use a try catch statement:
var barfoo;
try{
barfoo = d.bar.foobar.barfoo
}
catch(e){
barfoo = null;
}
More robust solution: check in any depth of the object
var Foo = {
"bar": {
"foobar": {
"barfoo": {
"ddd": 1
}
}
}
};
function checkProps(obj) {
var ref = obj, arg, i;
for (i = 1; i < arguments.length; i += 1) {
arg = arguments[i];
if(ref.hasOwnProperty(arg)){
ref = ref[arg]
} else {
return false;
}
}
return true;
}
//the function takes the object to search as first parameter and any other properties [,prop1,prop2,...]
console.log(checkProps(Foo, 'bar', 'foobar', 'barfoo', 'ddd'));
You can just do a single if statement with && - which does short circuit evaluation.
if (d
&& d.hasOwnProperty('bar')
&& d.bar.hasOwnProperty('foobar')
&& d.bar.foobar.hasOwnProperty('barfoo')
) {
// fancy things happen
}
The reason you use d.hasOwnProperty('bar') instead of just d.bar is in case something has polluted the object prototype.
If all you need to know is whether or not it exists, you could just do it with a try/catch
try{
if (Foo.bar.foobar.barfoo) {
//do stuff with your thingy because you know it exists
}
} catch(x) {
//you know it's no good/doesn't exist
}
I can't get the the conditional to work in this function, any help?
function headupdate(id, name, heading)
{
var order;
if (document.getElementById(heading).value === undefined)
{
order = 1;
}
else
{
order = document.getElementById(heading).value;
}
alert(order);
$.post('headingupdate.php', {id: id, name: name, value: heading, order: order},
function(response)
{
$('#resume').html(response)
}
)
};
You should check as following.
var head = document.getElementById(heading);
if(head!=null)
{
order = head.value;
}
else
{
order=1;
}
In response to your post title, I use typeof() to find if an element exists in the DOM:
if(typeof(document.getElementById('someElement')=='undefined')) {
alert('Element DNE');
}
Also, typeof() returns a string, so it needs to be in quotes for a conditional statement
"undefined"