Ron I
Ron I

Reputation: 4250

Checking for the last element in a JQuery each function

I have an object that I am iterating through using JQuery's each function. However, the solution posted in this stack overflow post doesn't work when I tried using the length property. I got undefined in the console when I tried getting a length property value, which I believe this is because I am iterating through an object and not an array.

My code:

$.each(attributes, function(key, value) {
        attrKey = key;
        attrVal = value;
        console.log(attributes.length); //returns undefined
       //do something if it is the last element
 });

Upvotes: 0

Views: 2741

Answers (3)

Vishnu Ravi
Vishnu Ravi

Reputation: 46

Try

var index = 1;
$.each(attributes, function(key, value) {
    if(Object.keys(attributes).length == index)
    { 
         // Do something
    }
    index++;
});

Upvotes: 1

Ron I
Ron I

Reputation: 4250

per @PaulFrench's comment:

length = Object.keys(attributes).length; 
if(n < length) {
         //do something
}

Upvotes: 0

smaili
smaili

Reputation: 1235

Try plain Javascript instead:

for (var key in attributes) {
  var value = attributes[key];
  // process key,value...
}

Edit:

If you're trying to get the last key/value in an object, you can't. Javascript objects are unordered, meaning that they do not keep track of when additional key/value assignments are made. If order is important, I would recommend changing attributes be an array of objects, where each object is a single key/value, or use a 3rd party library, like this - https://github.com/trentrichardson/Ordering.

If you'd like to get the number of keys in attributes, use Object.keys:

Object.keys(attributes).length

Upvotes: 2

Related Questions