Underscore.js: unexpected behavior with _.object function

Here is the description from the docs of the _.object function.

Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. If duplicate keys exist, the last value wins.

With this example, it works as expected. The key of "1" is assigned the value of "TEST1".

_.object(["1", "1"], ["TEST", "TEST1"])

>> Object {1: "TEST1"}

_.object(["1", "1"], ["TEST"])

>> Object {1: undefined}

On this last example, I'd expect the value to be "TEST", but it is undefined.

Is there a specific reason for this behavior?



The behavior is correct. The first call

_.object(["1", "1"], ["TEST", "TEST1"])

associates key 1 with TEST and key 1 with TEST1 (overriding the previous association).

The second call:

_.object(["1", "1"], ["TEST"])

has the same logic, but the second key 1 is associated with the element in the second position in the 'values' array, which is undefined.

PS: The code for _.object is this:

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, length = list.length; i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
    return result;

It seems they do specify that the arrays need to have the same length. From the code it is obvious that if the second array is larger, the last values will be ignored and if it is smaller, the last values will be undefined.

Need Your Help

UINavigation leftBarItem show back button and additional button

ios uinavigationcontroller

I have an app that opens with a split view controller, table on the left contains a list of customers, on the right is the users calendar. Selecting a customer from the table replaces the calendar ...

Collections.max(array) is Not Working - Java

java arrays

I am using Collections.max(array); to determine what the largest number in the selected array is. However when i use it, i get the error message: