dentalhero dentalhero - 1 year ago 151
jQuery Question

Check if Specific Key Exists in Json Array

I an trying to produce a check to determine if a specific key exists in a json array using jQuery. Specifically, if I see this key, I know that that no objects that I want to display on the page were returned from the server.

The simple check that I'm trying to use looks like this:

if (data.hasOwnProperty('Error - No records found in table')) {

The array that is returned from the server looks like this:

[{"Error - No records found in table": ""}]

Full Code:

var url = '';
var postData = $('#BranchSpecials').serialize();
var spinnerBig = $('.loadingSpinner');

var getClearanceItems = $.ajax({
type: 'Post',
url: url,
xhrFields: {
withCredentials: true
crossDomain: true,
data: postData,
dataType: 'json',
beforeSend: function(xhr) {;

getClearanceItems.done(function(data, jqXHR) {
var clearance = $("#clearance");

if (data.hasOwnProperty('Error - No records found in table')) {

var items = [];
$.each(data, function(i, item) {
items.push('<div class="item-block"><a href="' + url + item.ProdLink + '"><img src="' + item.ProdImage + '" width="104" height="104"/></a><div class="item-meta"><p class="desc"><a href="' + url + item.ProdLink + '">' + item.ProductDesc + '</a></p><p class="itemID">Item #: <a href="' + url + item.ProdLink + '" class="uline">' + item.ProductID + '</a></p></div></div>');


infinite: true,
slidesToShow: 4,
slidesToScroll: 4,
dots: true,
appendArrows: $('#controls'),
prevArrow: '<button type="button" class="btn btn-default"><i class="material-icons">chevron_left</i></button>',
nextArrow: '<button type="button" class="btn btn-default"><i class="material-icons">chevron_right</i></button>'

What is wrong with this check?

Answer Source

You are checking the property defined for the array not the object, if the array contains single object then get the first object from array and check

if(data[0].hasOwnProperty('Error - No records found in table'))

if multiple elements are there then try the other answer using some() by @AmirPopovich.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download