user1058398 February 2016

Is there a way to get the iteration number with angular foreach on an object

Is there any way I can get the iteration number inside an angular foreach (when iterating through an object like : {'foo': 'blah', 'blah': 'foo'} ? So with my iterator function in that case, value will be 'blah' and then 'foo' while key will be 'foo' and then 'blah'

Answers


Enjayy February 2016

Yes it is the second parameter that gets passed in to the foreach function call directly from the angular documentation

https://docs.angularjs.org/api/ng/function/angular.forEach

angular.forEach(obj, iterator, [context]);


Omri Aharon February 2016

Yes, like this:

angular.forEach(array, function (item, index) {
    //index
});


Mahantesh Kumbar February 2016

angular.forEach(var,function(value,key){
  console.log(key);
})


ste2425 February 2016

Angulars forEach when iterating an object doesn't tell you how many times its iterated that objects keys.

When iterating an array it doesn't tell you how many times its ran but its current position in the array. It's probably just me being pedantic but there is a difference.

However an alternative that could give its current position in the objects keys would be to use the native Object.keys(). It will return an array of the objects keys, you can then iterate over them like a normal array and get your current position in that array.

var obj = {'foo': 'blah', 'blah': 'foo'};

Object.keys(obj)
    .forEach(function (key, index) {
        console.log('Key', key, 'Value', obj[key]);
        console.log('Ive ran ', index);
    });

DOCS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Post Status

Asked in February 2016
Viewed 1,894 times
Voted 5
Answered 4 times

Search




Leave an answer