-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
51 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,25 @@ | ||
import forOwn from './forOwn' | ||
import has from './has' | ||
import toPath from './toPath' | ||
|
||
export default function get(value: object, path: string | string[], defaultValue?: any): any { | ||
/** | ||
* 根据 obj 对象的路径 path 获取值。 | ||
* | ||
* @param obj 要检索的对象 | ||
* @param path 属性路径 | ||
* @param [defaultValue] 默认值 | ||
* @returns 检索结果 | ||
*/ | ||
export default function get(obj: object, path: string | string[], defaultValue?: any): any { | ||
path = Array.isArray(path) ? path : toPath(path) | ||
const result: any = defaultValue | ||
const last: any = value | ||
let last: any = obj | ||
for (let i = 0, len = path.length; i < len; i++) { | ||
|
||
if (has(last, path[i])) { | ||
last = last[path[i]] | ||
if (i === len - 1) { | ||
return last | ||
} | ||
} else { | ||
return defaultValue | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters