0

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?

Thanks.

1
  • 1
    Why do you expect that last value to be test? The last index of the key "1" is 1, and the value at index 1 is undefined. Makes sense to me. Commented Dec 6, 2013 at 8:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I probably should have looked at the code myself before posting this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.