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 方法 #29

Open
Rain120 opened this issue Mar 24, 2022 · 1 comment
Open

实现一个 get 方法 #29

Rain120 opened this issue Mar 24, 2022 · 1 comment

Comments

@Rain120
Copy link
Owner

Rain120 commented Mar 24, 2022

题目

function get(obj, ...args) {
    // ...
}

const obj = {
    selector: {
        to: {
            toutiao: 'FE coder'
        }
    },
    target: [1, 2, {
        name: 'byted'
    }]
};

get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name');
// 输出结果:// ['FE coder', 1, 'byted']
@Rain120
Copy link
Owner Author

Rain120 commented Mar 24, 2022

function getValue(source, path, defaultValue = null) {
    const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.');
    let result = source;

    for (let key of paths) {
        // null 与 undefined 取属性会报错, 用Object包装一下
        result = Object(result)[key];
    }

    return result || defaultValue;
}

function get(obj, ...args) {
    return args.map(key => getValue(obj, key));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant