user1637281
user1637281

Reputation:

Incrementing through object properties?

Is it possible to increment ( not loop ) through object properties. I know that objects don't guarantee ordering but I want to increment through them any ways.

For example, for an array one can do:

arr[index++];

But this does not work for an object:

obj[key++];

as I do not think the ++ operator is defined for use on keys.

I don't want to have to build a complex object structure that stores indexes with keys. I want to do it natively.

I am well aware of the for-in structure but I want to increment as needed, not loop.

Upvotes: 2

Views: 2895

Answers (2)

Ilmari Karonen
Ilmari Karonen

Reputation: 50368

The ++ operator works on any number: it increments the number by one.

If the properties of your object are numbers, you could certainly use ++ to iterate over them:

var obj = { 1: "foo", 2: "bar", 3: "baz" };
var i = 1;
console.log( obj[i++] );
console.log( obj[i++] );
console.log( obj[i++] );

(Of course, one problem with this is that, in general, there's no guarantee that the properties of an object, even if numeric, would have to be consecutive numbers.)

Now, dystroy has already pretty well answered the actual question, so I won't repeat his answer here. I just wanted to add this bit to stress the fact that asking whether "the ++ operator is defined for use on keys" is missing the point: the ++ operator doesn't know or care about whether the value it's operating on is an array key or an object property name or the answer to life, the universe and everything. All it cares about is whether or not it is, or can be meaningfully interpreted as, a number.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382274

In recent browsers, you can use the keys array :

val = Object.keys(o)[i++];

Detailed example :

var keys = Object.keys(o);
for (var i=0; i<keys.length; i++) {
    var key = keys[i];
    console.log(key, o[key]);   
}

To be compatible with IE8, use this construct to iterate over keys :

for (var key in o) {
   console.log(key, o[key]);
}

If you don't want to iterate over inherited properties, use hasOwnProperty :

for (var key in o) {
    if (o.hasOwnProperty(key) console.log(key, o[key]);
}

Upvotes: 3

Related Questions