-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget.js
39 lines (37 loc) · 860 Bytes
/
get.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var curry2 = require('./internal/curry2')
var split = require('./split')
var reduce = require('./reduce')
/**
* Gets value from (nested) path in a collection.
*
* @param {(string|string[])} path - dot-string or string-array denoting path
* @param {(Object|Array)} collection - collection to get value from
* @returns {*} Returns value if found, `undefined` otherwise
*
* @example
* get('a.b', { a: { b: 42 } }) // => 42
*
* @example
* get(['a', 'b'], { a: { b: 42 } }) // => 42
*
* @example
* get('a.1', { a: [1, 2] }) // => 2
*
* @since 0.1.0
*/
function get (path, collection) {
if (typeof path === 'string') {
path = split('.', path)
}
if (!Array.isArray(path)) {
return undefined
}
return reduce(
function (acc, key) {
return acc && acc[key]
},
collection,
path
)
}
module.exports = curry2(get)