Ron I Ron I - 1 year ago 75
Javascript Question

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

Answer Source


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