(ECMAScript 2015 changes things, see update at end of answer.)
I have an array and an object. I want to iterate over the object properties while doing the same with the array, without explicitly declaring a counter.
I don't believe you can. Moreover, it's important to understand the that properties in the object have no order. You seem to be assuming you'll get "rose", then "sunflower", etc. That is simply not guaranteed. Many engines visit object property names in the order in which the properties were added to the object, and the order in which literal properties in an object initializer are added to the object is now (as of ES5 a couple of years back) specified, but visiting them in any particular order in for-in
is not specified behavior (similarly, Object.keys
is not sorted in any particular way), and a perfectly correct engine can visit them in any order it wants.
As such, with just the array and object you've shown, you have no reliable way to map those properties to the array entries.
As of ECMAScript 2015 (ES6), object properties have order now:
- Let keys be a new empty List.
- For each own property key P of O that is an integer index, in ascending numeric index order
- Add P as the last element of keys.
- For each own property key P of O that is a String but is not an integer index, in property creation order
- Add P as the last element of keys.
- For each own property key P of O that is a Symbol, in property creation order
- Add P as the last element of keys.
- Return keys.
Okay, so we know that they'll be visited in "creation" order, but in what order are they created by an object initializer? Good news: Object initializers are processed in source code order, so that's deterministic. Your rose
comes before your sunflower
, etc.
This means that while you still can't do what you want without explicitly declaring and maintaining an index variable, you can relate that array and that object reliably:
// Works as of ES6
var colors = ['red','yellow','purple','blue'];
var flowers = {'rose':'','sunflower':'','violet':'','hydrangea':''};
let i = 0;
for (prop in flowers) {
flowers[prop] = colors[i++];
}
I'm not suggesting doing it, but it's possible now, on compliant engines.