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

web开发作者:dayu日期:10天前点击:3
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

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

原文地址:http://www.cnblogs.com/xtreme/p/7240035.html


下一篇       上一篇