Skip to content

对象属性支持路径查询

js
/**
 * @params  源对象
 * @params  路径参数字符串
 * @returns 对象目标属性值
 */
function _get(object, path) {
    const reg = /\[(\w+)\]/g
    path = path.replace(reg, '.$1').split('.')
    let index = 0
    let length = path.length
    while (object && index < length) {
        let key = path[index++]
        object = object[key]
    }
    return object
}

// test case 
const obj = {
    a: {
        b: {
            c: [
                [{
                    d: 'test nest value'
                }],
                {
                    d: 1
                },
                {
                    d: 2
                }
            ],
            e: {
                f: 'ff'
            }
        }
    }
}

console.log(_get(obj, 'a.b.c[0][0].d'), 'woo result!')