js对象通过属性路径获取属性值 - getPropByPath

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) {
            let key = keyArr[i];
            if (key in tempObj) {
                tempObj = tempObj[key];
            } else {
                throw new Error('[iView warn]: please transfer a valid prop path to form item!');
            }
        }
        return {
            o: tempObj,
            k: keyArr[i],
            v: tempObj[keyArr[i]]
        };
    }

如: var obj = {name:'objname', items:[{value: 0},{value: 1}]}, path = 'items.0.value';

   console.log( getPropByPath(obj, path).v );

结果: 0

posted @ 2017-07-26 15:41  【云】风过无痕  阅读(1096)  评论(0编辑  收藏  举报