Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Twlig opened this issue Jul 18, 2022 · 0 comments
Open

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

Twlig opened this issue Jul 18, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Jul 18, 2022

实现一个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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant