Twlig / issuesBlog

MIT License
3 stars 0 forks source link

实现一个get函数,获取一个深嵌套对象中的值 #114

Open Twlig opened 2 years ago

Twlig commented 2 years ago

实现一个get函数,获取一个深嵌套对象中的值 关键点在于正则表达式

function splitKey(key) {
    return key.split('.').map(item => {
        const match = /([\d\w_-]*)\[(\d+)\]/g.exec(item)
        return match ? [match[1], parseInt(match[2])] : item
    })
}
function get(object, key) {
    const keyArr = splitKey(key)
    let ans = object
    for(item of keyArr) {
        if(Array.isArray(item)) {
            ans = ans[item[0]][item[1]]
        } else {
            ans = ans[item]
        }
    }
    return ans
}
var object = { 'a': [{ 'b': { 'c': 3 } }] };
get(object, 'a[0].b.c');
//应该返回 3