mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-10 10:57:49 +00:00
Merge pull request #454 from pistacchio/master
Added default value to `_.result`.
This commit is contained in:
10
lodash.js
10
lodash.js
@@ -7247,13 +7247,14 @@
|
|||||||
* Resolves the value of property `key` on `object`. If `key` is a function
|
* Resolves the value of property `key` on `object`. If `key` is a function
|
||||||
* it will be invoked with the `this` binding of `object` and its result returned,
|
* it will be invoked with the `this` binding of `object` and its result returned,
|
||||||
* else the property value is returned. If `object` is falsey then `undefined`
|
* else the property value is returned. If `object` is falsey then `undefined`
|
||||||
* is returned.
|
* is returned. If property `key` is not set, return defaultValue if defined;
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @memberOf _
|
* @memberOf _
|
||||||
* @category Utilities
|
* @category Utilities
|
||||||
* @param {Object} object The object to inspect.
|
* @param {Object} object The object to inspect.
|
||||||
* @param {string} key The name of the property to resolve.
|
* @param {string} key The name of the property to resolve.
|
||||||
|
* @param {*} [defaultValue] The value to return if object doesn't have key.
|
||||||
* @returns {*} Returns the resolved value.
|
* @returns {*} Returns the resolved value.
|
||||||
* @example
|
* @example
|
||||||
*
|
*
|
||||||
@@ -7269,10 +7270,13 @@
|
|||||||
*
|
*
|
||||||
* _.result(object, 'stuff');
|
* _.result(object, 'stuff');
|
||||||
* // => 'nonsense'
|
* // => 'nonsense'
|
||||||
|
|
||||||
|
* _.result(object, 'pizza', 'spaghetti');
|
||||||
|
* // => 'spaghetti'
|
||||||
*/
|
*/
|
||||||
function result(object, key) {
|
function result(object, key, defaultValue) {
|
||||||
if (object) {
|
if (object) {
|
||||||
var value = object[key];
|
var value = typeof object[key] !== 'undefined' ? object[key] : defaultValue;
|
||||||
return isFunction(value) ? object[key]() : value;
|
return isFunction(value) ? object[key]() : value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
11
test/test.js
11
test/test.js
@@ -6600,6 +6600,17 @@
|
|||||||
|
|
||||||
deepEqual(actual, expected);
|
deepEqual(actual, expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should return the default value if key is not found', 2, function() {
|
||||||
|
var object = {
|
||||||
|
'a': 1,
|
||||||
|
'b': 2
|
||||||
|
}
|
||||||
|
|
||||||
|
strictEqual(_.result(object, 'c', 3), 3);
|
||||||
|
strictEqual(_.result(object, 'c'), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
}());
|
}());
|
||||||
|
|
||||||
/*--------------------------------------------------------------------------*/
|
/*--------------------------------------------------------------------------*/
|
||||||
|
|||||||
Reference in New Issue
Block a user