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

Categories

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...