Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

实现一个 get 方法 #29

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago

题目

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 commented 2 years ago
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));
}