mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-31 15:27:50 +00:00
added oneToMany option to _.invert()
This commit is contained in:
16
lodash.js
16
lodash.js
@@ -2540,21 +2540,31 @@
|
||||
* @memberOf _
|
||||
* @category Objects
|
||||
* @param {Object} object The object to invert.
|
||||
* @param {boolean} oneToMany allow multiple values for each key in the inverted result
|
||||
* @returns {Object} Returns the created inverted object.
|
||||
* @example
|
||||
*
|
||||
* _.invert({ 'first': 'fred', 'second': 'barney' });
|
||||
* // => { 'fred': 'first', 'barney': 'second' }
|
||||
*
|
||||
* _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }, true);
|
||||
* // => { 'fred': ['first', 'third'], 'barney': ['second'] }
|
||||
*/
|
||||
function invert(object) {
|
||||
function invert(object, oneToMany) {
|
||||
var index = -1,
|
||||
props = keys(object),
|
||||
length = props.length,
|
||||
result = {};
|
||||
|
||||
while (++index < length) {
|
||||
var key = props[index];
|
||||
result[object[key]] = key;
|
||||
var key = props[index],
|
||||
value = object[key];
|
||||
if (oneToMany) {
|
||||
result[value] = result[value] || [];
|
||||
result[value].push(key);
|
||||
} else {
|
||||
result[value] = key;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -3306,6 +3306,12 @@
|
||||
var object = { '0': 'a', '1': 'b', 'length': 2 };
|
||||
deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' });
|
||||
});
|
||||
|
||||
test('should accept the one-to-many flag', 1, function() {
|
||||
var object = { '0': 'a', '1': 'b', '2': 'a' };
|
||||
deepEqual(_.invert(object, true), { 'a': ['0', '2'], 'b': ['1'] });
|
||||
});
|
||||
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Reference in New Issue
Block a user