Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

js 访问用字符串访问对象中的属性问题

    var obj = {
        a: {
            b: {
                c: 1
            }
        }
    }

想用'a.b.c' 能直接访问到1
怎么写 不是用obj.a.b.c 也不是用obj'a'['c'],
用个函数来转换还是


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function getPropByPath(obj, path) {
    let tempObj = obj;
    path = path.replace(/[(w+)]/g, '.$1');
    path = path.replace(/^./, '');

    let keyArr = path.split('.');
    let i = 0;
    for (let len = keyArr.length; i < len - 1; ++i) {
        if (!tempObj) break;
        let key = keyArr[i];
        if (key in tempObj) {
            tempObj = tempObj[key];
        } else {
            return null
            //break;
        }
    }
    return tempObj ? tempObj[keyArr[i]] : null
}

getPropByPath(obj, 'a.b.c') // 1
getPropByPath(obj, 'a[b][c]') // 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...