Reputation: 1019
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.
Upvotes: 0
Views: 173
Reputation: 27823
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.
Upvotes: 2