How to get jQuery object size

I store key-value pairs in a div container using:

$( '#div_id').data( key, value);

In the end, I need to check if anything is stored in this div container.

So first, I get the content by calling:

var data = $( '#div_id').data();

Then, to check its size with data.length or data.size.

But both functions do not exist. Since I know that the data function in jquery returns an object, so I should be able to get the size of this object.

How to get the size of an object returned by a data function in jquery?

+5
source share
4 answers

Objects do not have a "size". You could calculate its properties:

function getPropertyCount(obj) {
    var count = 0,
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }

    return count;
}

Using:

alert(getPropertyCount(data));
+10
source

/ / node.

var data = $( '#div_id').data();

, node, event handlers, , - .

, :

$('#div_id').data('mydata', {});
/* ... */
$('#div_id').data('mydata')[key] = value;

. Javascript .length. , :

var mylen = 0;
for(var prop in $('#div_id').data('mydata')) {
    mylen++;  
}

.hasOwnProperty(), , - .

+2

, "" ? , , , .

.

var myStuff = {};
myStuff.date = new Date();
myStuff.name = "Santa Claus";
myStuff.lifeStory = "Once upon a time...";
$('#div_id').data('myData', myStuff);

, , ...

var data = $('#div_id').data('myData');

Keep in mind that JavaScript / Map objects do not have a “length” or “size” method / property, so if you need to check if it contains anything, this general function should work.

function isObjEmpty(obj){
  for(var i in obj){
    return false;
  }
  return true;
}
+1
source

Javascript objects do not have a length property. But you can easily compute it with a simple jQuery function.

$.fn.dataLength = function () {
    var i,
        n = 0,
        t = $(this);
    for (i in t.data()) {
        n += 1;
    }

    return n;
}

Then use it with $ ('# div_id'). dataLength ()

EDIT

Check out the other answers about the data structure in .data and the .hasOwnProperty validation

0
source

All Articles