一段需要铭记的代码...

153 阅读1分钟
function getPathValue(source, ...paths) {
    const res = Array(paths.length);

    function getPathValue(path) {
        const keyArr = path.split('.');

        return keyArr.reduce((value, item) => {
            if (item.match(/[(.+?)]/)) {
                return value[item.split('[')[0]][RegExp.$1];
            }
            return value[item];
        }, source);
    }

    paths.forEach((path, i) => {
        res[i] = getPathValue(path);
    })

    return res;
}

const o = {
    a: {
        b: [{c: 1}, {d: {e: 3}}],
        d: '222'
    }
};

console.log(getPathValue(o, 'a[d]', 'a.b[0]', 'a.b[0].c', 'a.b[1].d.e', 'lalala'));