object/getPath.jsjavascript
import { toPath } from '../_internal/path'
/**
* 根据点号或括号路径读取嵌套属性。
* @function getPath
* @memberof module:object
* @param {Object} object 要读取的对象
* @param {string|number|Array<string|number>} path 属性路径
* @param {*} [defaultValue] 路径不存在或值为 undefined 时的默认值
* @returns {*} 属性值或默认值
* @throws {TypeError} path 类型不正确时抛出
*/
function getPath(object, path, defaultValue) {
const parts = toPath(path)
let current = object
for (const part of parts) {
if (current === null || current === undefined || !(part in Object(current))) return defaultValue
current = current[part]
}
return current === undefined ? defaultValue : current
}
export default getPath