3

Given an object x, are the results of _.keys(x) and _.values(x) guaranteed to be sequentially aligned?

This is, for a given index i, _.keys(x)[i] and _.values(x)[i] should refer to the same key-value entry in x.

x is assumed to remain unchanged between calls to one and the other function.

Is there any reason why I could get ordering issues?

deprecated
  • 5,142
  • 3
  • 41
  • 62
  • No it isn't. I don't care about the particular order I get, but about its consistency within the browser is executing my code. – deprecated May 29 '13 at 09:10

1 Answers1

3

The implementation of those functions both use a for (... in ...) loop (or Object.keys if it is present).

Some JS engines report that they do not guarantee order for such a loop (from MDN):

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

From the delete operator notes, the best way to guarantee the correctness of the order across all browsers is to "either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects."

Related question: Elements order in a "for (… in …)" loop

Community
  • 1
  • 1
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • 1
    The standard itself says that property order in a JavaScript object is, more or less, implementation defined. There are some links to the relevant sections of the ES5 [over here](http://stackoverflow.com/a/10624559/479863). – mu is too short May 29 '13 at 16:29