How to tell if JSON object is empty in jQuery - javascript

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

Related

Javascript filter array empty objects

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

Checking for empty data in JSON in JavaScript

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

Validate empty object

I have an variable that devolves an empty object, and i need validate thas this variable have a value.
guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (value1 === {}) {
alert('It is necessary to select an option.');
return;
}
}
When it arrives in the debug line in the If statement, although the value of the variable is {}, when evaluating the condition the result is false.
¿Someone could help me about how can i do that validation?
If you get a object, then, do you need to proccess that object to verify if exist a property
Try this:
guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (typeof value1 === 'object' && Object.keys(value1).length === 0) {
alert('It is necessary to select an option.');
return;
}
}
guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (Object.keys(value1).length === 0) {
alert('It is necessary to select an option.');
return;
}
} // This Will Work as your requirement
You can't do value1 === {} for the same reason that {} === {} is false. The reason for this is javascript compares objects by reference, not by value. Which means it checks if the objects occupy the same memory location.
You can try something like
Object.prototype.isEmpty = function() {
for(var key in this) {
if(this.hasOwnProperty(key))
return false;
}
return true;
}
Then you can test if it's empty
if (value1.isEmpty()) {
alert('It is necessary to select an option.');
return;
}
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key)){
return false;
}
}
return true;
}
var x = {};
if(isEmpty(x)){
alert('It is necessary to select an option.');
return;
}else{
}

JavaScript: Execute function only if all items in array are true?

I have this code:
// Required fields is an array of objects
required_fields.each(function() {
// Check each field: If it has no value, do nothing.
if( !$(this).val() ) {
return false;
}
// If all the fields are there, do something.
else {
alert('Doing something.');
}
});
I'm sure you can see the problem. Having the alert in the .each() function causes the alert to trigger for every item in the array. But what I want is to only trigger the event if ALL of the array items have a value—that is, if none return false.
What is the correct way to trigger something only if all the array items pass?
Just implement a little counter for each value.
var valueCount = 0;
required_fields.each(function () {
if (!$(this).val()) {
return false;
} else {
valueCount++; // increment to say has value
}
});
if (valueCount == required_feilds.length) {
alert('Doing something.');
}
You can use Array.prototype.every which will short circuit when a falsy value is returned:
var isTrue = [].every.call(required_fields, function(el) {
return $(el).val();
});
if (isTrue) {
console.log('Doing something');
}
I don't think you have an array but a jQuery object which is array like (got length and 0, 1, ... properties) So you can (ab)use the native Array prototype by setting the context with .call:
var every = Array.prototype.every;
every.call({ '0': 'a', '1': 'b', length: 2 }, console.log.bind(console));
// will output
// ['a', 0]
// ['b', 1]
Now that I think of it jQuery.fn.each will also short circuit if false is returned.
Two main options stand out:
1: Write a simple function that takes an array of jQuery objects and returns true if all items in the array have value
var allHaveValue = function(array){
for(var i = 0; i < array.length; i++){
if(!$(array[i]).val()){
return false;
}
}
return true;
};
// For your example
if(allHaveValue(required_fields)){
// Proceed
} else{
// Handle errors
}
The other alternative is doing the same thing but using the underscore.js function for [every][1]
[1]: http://underscorejs.org/#every which does the same thing. The call would look like:
var allHaveValue = _.every(required_fields, function(item){
return $(item).val();
});
if(allHaveValue)}{
// Proceed
} else{
// Handle errors
}

How can I tell 'Whether a Javascript object exists on my page'?

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"

Categories